Solve Search Insert Position Using Binary Search
Company: Amazon
Role: Data Scientist
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
##### Scenario
Live coding round for an Amazon Applied Scientist position; candidate must solve LeetCode 35 (Search Insert Position) without helper libraries.
##### Question
Given a sorted array of distinct integers nums and an integer target, return the index if target exists; otherwise return the index where it would be inserted to keep order. Implement the solution using an explicit binary search (no built-in bisect).
##### Hints
Iterative or recursive binary search, O(log n) time, manage low/high pointers and insertion position when loop exits.
Quick Answer: This question evaluates proficiency in binary search, algorithmic implementation on sorted arrays, and understanding of time complexity and index management.
Given a sorted array of distinct integers nums and an integer target, return the index of target if it is present. Otherwise, return the index where target should be inserted to maintain ascending order. Implement the solution using an explicit binary search (do not use built-in bisect).
Constraints
- 0 <= len(nums) <= 100000
- nums is sorted in strictly increasing order
- All elements in nums are distinct
- -10^9 <= nums[i] <= 10^9
- -10^9 <= target <= 10^9
- Expected time complexity: O(log n)
- Do not use built-in bisect functions
Solution
from typing import List
def search_insert(nums: List[int], target: int) -> int:
low, high = 0, len(nums) - 1
while low <= high:
mid = (low + high) // 2
if nums[mid] == target:
return mid
if nums[mid] < target:
low = mid + 1
else:
high = mid - 1
return low
Explanation
Classic binary search: keep narrowing the search range using low and high. If target is found, return its index. Otherwise, when the loop finishes, low is the smallest index where target can be inserted to maintain order.
Time complexity: O(log n). Space complexity: O(1).
Hints
- Maintain two pointers low and high bounding the current search range.
- Compute mid = (low + high) // 2 and compare nums[mid] with target.
- When the loop ends, low will be the correct insertion index.