⬅ Previous Topic
Find Upper Bound in Sorted ArrayNext Topic ⮕
Floor and Ceil in Sorted Array⬅ Previous Topic
Find Upper Bound in Sorted ArrayNext Topic ⮕
Floor and Ceil in Sorted ArrayTopic Contents
Given a sorted array of distinct integers and a target number x
, your task is to find the insert position of x
.
This means you must return the index where x
is located in the array. If it is not present, return the index where it should be inserted in order to keep the array sorted.
This problem is also known as finding the lower bound — the first index where an element is greater than or equal to x
.
arr
of distinct integers and a target value x
.low = 0
, high = arr.length - 1
, ans = arr.length
.low ≤ high
:mid = Math.floor((low + high) / 2)
.arr[mid] ≥ x
, update ans = mid
and move left: high = mid - 1
.low = mid + 1
.ans
as the correct insert position.def search_insert_position(arr, x):
n = len(arr)
low, high = 0, n - 1
ans = n
while low <= high:
mid = (low + high) // 2
if arr[mid] >= x:
ans = mid
high = mid - 1
else:
low = mid + 1
return ans
# Sample Input
arr = [1, 3, 5, 6]
target = 2
print("Insert Position:", search_insert_position(arr, target))
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(1) | The target is found at the middle index on the first comparison, requiring only one iteration. |
Average Case | O(log n) | Binary search halves the search space in each iteration, so on average, it takes log n steps to find the insert position. |
Average Case | O(log n) | In the worst case, the entire array must be searched logarithmically to determine where the target should be inserted. |
O(1)
Explanation: The algorithm operates in-place using only a constant amount of memory — just a few integer variables for low, high, mid, and ans.
⬅ Previous Topic
Find Upper Bound in Sorted ArrayNext Topic ⮕
Floor and Ceil in Sorted ArrayYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.