Understanding the Problem
Suppose you are given a sorted array, and you want to find the correct position to insert a target number x
so that the array remains sorted. This problem is not just about checking if x
is present; it's about finding the position where it could be inserted — this is called the lower bound.
For example, if arr = [1, 3, 5, 6]
and x = 5
, the output should be 2
because 5
is already at index 2
.
But if x = 4
, then the correct insert position is 2
because it would go between 3
and 5
.
Step-by-Step Intuition
Let’s solve this using a technique called binary search, which is perfect for sorted arrays. Instead of checking every position one by one, we’ll divide the array in halves, zero in on the region where x
could go, and find the first index where arr[i] ≥ x
.
Step 1: Initialize Search Range
We start with two pointers:
low = 0
(start of the array)
high = n - 1
(end of the array)
We also define ans = n
(default answer is the end of array, in case x
is greater than all elements).
Step 2: Binary Search Loop
Repeat while low ≤ high
:
- Calculate
mid = Math.floor((low + high) / 2)
- If
arr[mid] ≥ x
:
- This index might be the correct insert position, so set
ans = mid
- Move search to the left half:
high = mid - 1
- Else:
x
is greater than arr[mid]
, so move right: low = mid + 1
Step 3: Final Answer
After the loop ends, ans
will hold the first index where x
can be inserted to maintain the sorted order.
Example Walkthrough
Let’s try with arr = [1, 3, 5, 6]
and x = 4
.
low = 0
, high = 3
mid = 1
→ arr[1] = 3
→ 3 < 4 → move right → low = 2
mid = 2
→ arr[2] = 5
→ 5 ≥ 4 → ans = 2
, high = 1
- Loop ends → Final answer:
2
Handling Edge Cases
- x is smaller than all elements → e.g.,
x = 0
→ insert at index 0
- x is greater than all elements → e.g.,
x = 10
→ insert at index arr.length
- x is equal to an existing value → insert at the first occurrence (lower bound)
Why Binary Search?
Binary search gives us an efficient way to solve this in O(log n)
time instead of scanning every element. This is especially useful for large arrays.
Comments
Loading comments...