Search Insert Position
LeetCode Problem #35 (Easy)
Problem Statement
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
Testcases
Prerequisite Knowledge
Binary Search
Refer to the Prerequisite Knowledge section in Random Pick with Weight:
Algorithm
Binary Search Approach
In this approach, we perform in-place sorting by taking two parameters of comparison into consideration.
Initialize two pointer variables to point to the extreme ends of the array.
Iterate until the condition (left <= right) breaks.
Calculate the mid value such that overflow is avoided.
If the target is found in the array, return the index value.
If the target is greater than the mid value, the searching proceeds in the right half of the array.
If the target is less than the mid value, the searching proceeds in the left half of the array.
If the code exits the loop
a. This means that left >= right + 1.
b. But, the target index is between [left, right + 1], so left <= right.
c. From a and b, left = right + 1.
So the index to be returned is at [left, left]->left or [right + 1, right + 1]->right + 1.
Illustration
Consider the array [1, 3, 5, 6, 8], and target = 7.
In the first pass, the search region spans the entire array.
In the second pass, since 7 > 5, we continue the search in the right half of the array by moving the left pointer up to the index, mid + 1.
In the third pass, since 7 > 6, we continue the search in the right half of the array by moving the left pointer up to the index, mid + 1.
In the fourth pass, since 7 < 8, we continue the search by moving the right pointer down to the index, mid - 1.
Here, the value of the the left pointer becomes greater than the right pointer so the loop exits. The position of the left pointer or the position of the right pointer + 1 is the place where 7 must be inserted.
Code
Last updated
Was this helpful?