Bird
Raised Fist0
Interview Prepmodified-binary-searcheasyAmazonGoogle

Search Insert Position

Choose your preparation mode4 modes available
</>
IDE
def searchInsert(nums: list[int], target: int) -> int:public int searchInsert(int[] nums, int target)int searchInsert(vector<int> &nums, int target)function searchInsert(nums, target)
def searchInsert(nums, target):
    # Write your solution here
    pass
class Solution {
    public int searchInsert(int[] nums, int target) {
        // Write your solution here
        return 0;
    }
}
#include <vector>
using namespace std;

int searchInsert(vector<int> &nums, int target) {
    // Write your solution here
    return 0;
}
function searchInsert(nums, target) {
    // Write your solution here
}
Coming soon
0/10
Common Bugs to Avoid
Wrong: len(nums)Returning length of array unconditionally when target not found, ignoring correct insertion point.✅ Return left boundary index after binary search loop ends instead of len(nums) always.
Wrong: 0Always returning 0 without searching, ignoring target position.✅ Implement binary search to find correct insertion index instead of constant return.
Wrong: Index off by one (e.g., 1 instead of 0 or 3 instead of 4)Off-by-one error in updating left or right pointers or mid calculation in binary search.✅ Use mid = left + (right - left) // 2 and update left = mid + 1 or right = mid correctly.
Wrong: Runtime error or infinite loopIncorrect loop condition or pointer updates causing infinite loop or out-of-bounds access.✅ Ensure while loop condition is left <= right and pointers update properly to avoid infinite loops.
✓
Test Cases
t1_01basic
Input{"nums":[1,3,5,6],"target":5}
Expected2

Target 5 is found at index 2.

t1_02basic
Input{"nums":[1,3,5,6],"target":2}
Expected1

Target 2 not found; should be inserted at index 1 to maintain order.

t2_01edge
Input{"nums":[],"target":5}
Expected0

Empty array; target should be inserted at index 0.

t2_02edge
Input{"nums":[10],"target":5}
Expected0

Single element array; target less than element, insert at 0.

t2_03edge
Input{"nums":[10],"target":15}
Expected1

Single element array; target greater than element, insert at 1.

t2_04edge
Input{"nums":[1,3,5,6],"target":7}
Expected4

Target greater than all elements; insert at end index 4.

t3_01corner
Input{"nums":[1,3,5,6],"target":1}
Expected0

Target equals first element; should return index 0.

t3_02corner
Input{"nums":[1,3,5,6],"target":6}
Expected3

Target equals last element; should return last index 3.

t3_03corner
Input{"nums":[1,3,5,6],"target":4}
Expected2

Target 4 not found; should be inserted at index 2 between 3 and 5.

t4_01performance
Input{"nums":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100000],"target":50000}
⏱ Performance - must finish in 2000ms

n=100000, O(log n) binary search must complete within 2 seconds.

Practice

(1/5)
1. You are given an array that was originally sorted in ascending order but then rotated at some unknown pivot. The array may contain duplicates. Your task is to find the minimum element efficiently. Which approach best guarantees an optimal solution for this problem?
easy
A. Use a simple linear scan to find the minimum element by checking all elements.
B. Use a greedy approach that picks the smallest element seen so far while iterating from the start.
C. Use a dynamic programming approach to store minimum values for subarrays and combine results.
D. Use a modified binary search that handles duplicates by shrinking the search space when elements at mid and high are equal.

Solution

  1. Step 1: Understand problem constraints

    The array is rotated and may contain duplicates, which complicates the binary search because duplicates can hide the pivot.
  2. Step 2: Identify suitable algorithm

    Modified binary search that shrinks the search space when duplicates are encountered ensures correctness and efficiency on average.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Modified binary search handles duplicates correctly [OK]
Hint: Duplicates require shrinking high pointer in binary search [OK]
Common Mistakes:
  • Assuming simple binary search works without handling duplicates
  • Using greedy or DP unnecessarily
2. You are given an array of positions of balls on a number line and a number m. You want to place m balls in these positions such that the minimum distance between any two balls is maximized. Which algorithmic approach guarantees finding the optimal minimum distance efficiently?
easy
A. Binary search on the answer space combined with a greedy feasibility check
B. Greedy placement by always placing balls at the closest possible positions without backtracking
C. Dynamic programming to consider all subsets of positions and their minimum distances
D. Sorting the positions and then using a sliding window to find the maximum minimum distance

Solution

  1. Step 1: Understand the problem structure

    The problem asks to maximize the minimum distance between placed balls, which is a classic optimization problem over a numeric answer space.
  2. Step 2: Identify the correct approach

    Binary search on the answer space (possible distances) combined with a greedy feasibility check efficiently finds the maximum minimum distance. Greedy alone or DP are either incorrect or inefficient.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Binary search narrows down distance candidates efficiently [OK]
Hint: Maximize minimum distance -> binary search on answer space [OK]
Common Mistakes:
  • Thinking greedy alone suffices without binary search
  • Using DP which is inefficient here
3. What is the time complexity of counting occurrences of a target in a sorted array using binary search to find left and right boundaries?
medium
A. O(n) because you must scan the array to count
B. O(log n) because binary search halves the search space each step
C. O(log n * log n) because two binary searches are performed
D. O(1) because built-in functions are optimized

Solution

  1. Step 1: Analyze binary search calls

    Two binary searches are performed independently, each O(log n).
  2. Step 2: Combine complexities

    Total time is O(log n) + O(log n) = O(log n), since constants are ignored.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Two binary searches do not multiply complexities [OK]
Hint: Two O(log n) calls sum to O(log n) [OK]
Common Mistakes:
  • Confusing two calls as O(log n * log n)
  • Assuming linear scan is needed
  • Believing built-in functions run in O(1)
4. The following code attempts to find the k-th smallest number in an m x n multiplication table. Which line contains a subtle bug that can cause incorrect results for large inputs?
medium
A. Line 4: count = 0
B. Line 6: count += x // i # missing min with n
C. Line 8: if count >= k:
D. Line 13: mid = (low + high) // 2

Solution

  1. Step 1: Identify counting logic

    The counting function must cap counts per row by n, since each row has only n elements.
  2. Step 2: Analyze line 6

    Line 6 adds x // i without min(n, x // i), causing overcounting when x // i > n, leading to incorrect binary search decisions.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Bug causes wrong counts and incorrect final answer [OK]
Hint: Count per row capped by n to avoid overcounting [OK]
Common Mistakes:
  • Forgetting min(n, x//i) in counting
  • Incorrect mid calculation
5. Consider the following buggy code snippet for finding the pivot in a rotated sorted array. Which line contains the subtle bug that can cause incorrect pivot detection?
medium
A. if nums[mid] > nums[high]: -- comparison logic is correct
B. mid = (low + high) / 2 -- mid should be integer index, not float
C. low = mid + 1 -- updating low is correct when nums[mid] > nums[high]
D. return low -- returning low as pivot is correct

Solution

  1. Step 1: Identify mid calculation issue

    mid is computed using division '/', which returns float in Python 3, causing invalid indexing.
  2. Step 2: Impact of float mid

    Using float as index causes runtime error or incorrect behavior; integer division '//' is required.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Changing '/' to '//' fixes the bug [OK]
Hint: mid must be integer index [OK]
Common Mistakes:
  • Using '/' instead of '//' in Python
  • Misplaced comparison operators
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard