Introduction
The Search Insert Position problem involves finding the index of a target element in a sorted array.
If the target element is not present:
- return the index where it should be inserted
- while maintaining sorted order
Given a sorted array arr[] and a target value x, the task is to:
- return the target index if found
- otherwise return the correct insertion position
This problem helps in understanding:
- Binary Search
- insertion logic
- sorted array traversal
- efficient searching techniques
Example
Input: arr[] = [1,3,5,6]x = 5
Output: 2
Explanation:
Element 5 exists at index 2.
Input: arr[] = [1,3,5,6]
x = 2
Output: 1
Explanation:
2 should be inserted at index 1
to maintain sorted order.
Constraints
1 <= n <= 10^5-10^9 <= arr[i] <= 10^9-10^9 <= x <= 10^9Array is sorted
Approach 1 : Brute Force (Linear Search)
Explanation
The simplest way to solve this problem is:
- Traverse the array sequentially
- Find the first element:
- greater than or equal to target
- Return its index
This approach works but does not utilize the sorted property efficiently.
Steps
- Traverse the array.
- Check:
- arr[i] >= target
- If condition becomes true:
- return index
- If traversal completes:
- return array size
Dry Run
Input Array:[1,3,5,6]
Target = 2
Traverse 1:
1 < 2
Continue traversal
Traverse 3:
3 >= 2
Correct insertion position = 1
Return 1
Brute Force Code
Complexity Analysis
Time Complexity: O(n)Explanation:
Elements are checked sequentially.
Space Complexity: O(1)
Explanation:
No extra data structures are used.
Approach 2 : Optimized Solution (Binary Search)
Explanation
Since the array is sorted, Binary Search can efficiently find:
- the target index
- or correct insertion position
The idea is:
- Find middle element
- Compare middle element with target
- Move:
- left pointer
- right pointer
If target is not found:
- left pointer finally represents the correct insertion position
Steps
- Initialize:
- left = 0
- right = n - 1
- While left ≤ right:
- find middle index
- If target found:
- return middle index
- If target greater:
- move left pointer
- Otherwise:
- move right pointer
- Return left pointer.
Dry Run
Input Array:[1,3,5,6]
Target = 2
Initially:
left = 0
right = 3
Middle = 1
arr[1] = 3
3 > 2
Move right pointer
right = 0
Middle = 0
arr[0] = 1
1 < 2
Move left pointer
left = 1
Traversal ends
Correct insert position = 1
Return 1
Optimized Code
Complexity Analysis
Time Complexity: O(log n)Explanation:
Search space is reduced by half in every iteration.
Space Complexity: O(1)
Explanation:
No extra data structures are used.
Edge Cases