Skip to content

Commit 04c43fa

Browse files
committed
Search Insert position
1 parent 67de492 commit 04c43fa

File tree

4 files changed

+209
-0
lines changed

4 files changed

+209
-0
lines changed
Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
# 35. Search Insert Position
2+
3+
**Difficulty:** Easy
4+
**Category:** Arrays, Binary Search
5+
**Leetcode Link:** [Problem Link](https://leetcode.com/problems/search-insert-position/)
6+
7+
---
8+
9+
## 📝 Introduction
10+
11+
Given a sorted array of distinct integers `arr[]` and a target value `x`, determine the index of `x` in the array.
12+
If `x` is not present, return the index at which it should be inserted to maintain the sorted order.
13+
14+
---
15+
16+
## 💡 Approach & Key Insights
17+
18+
The key insight is to use Binary Search to find the index of the target element. If the element is not found, Binary Search can also help determine the correct insertion position — this is known as the “lower bound” of the target value.
19+
20+
- If `arr[mid] == x`, return mid.
21+
- If `arr[mid] < x`, discard the left half.
22+
- If `arr[mid] > x`, it could be a possible answer; store mid and continue to the left half.
23+
24+
This ensures an efficient O(logN) solution instead of scanning the entire array.
25+
26+
---
27+
28+
## 🛠️ Breakdown of Approaches
29+
30+
### 1️⃣ Brute Force / Naive Approach
31+
32+
- **Explanation:**
33+
Linearly scan the array from the beginning. If `arr[i] >= x`, return index `i`. If no such element is found, return `n` (length of the array) — meaning `x` should be inserted at the end.
34+
35+
- **Time Complexity:** O(N) - May require scanning the entire array in the worst case.
36+
- **Space Complexity:** O(1) - No extra space used.
37+
38+
- **Example/Dry Run:**
39+
40+
```plaintext
41+
Input: arr[] = [1, 2, 4, 7], x = 6
42+
43+
Step 1: Check 1 < 6 → continue
44+
Step 2: Check 2 < 6 → continue
45+
Step 3: Check 4 < 6 → continue
46+
Step 4: Check 7 >= 6 → return index 3
47+
48+
Output: 3
49+
```
50+
51+
---
52+
53+
### 2️⃣ Optimized Approach
54+
55+
- **Explanation:**
56+
Use Binary Search to efficiently find the first element that is greater than or equal to `x`. If such an element is found, return its index. Otherwise, return the array's length (insert at the end).
57+
58+
- **Time Complexity:** O(logN) - Binary search halves the search space each iteration.
59+
- **Space Complexity:** O(1) - Only a few pointers and variables used.
60+
61+
- **Example/Dry Run:**
62+
63+
```plaintext
64+
Input: arr[] = [1, 2, 4, 7], x = 6
65+
66+
low = 0, high = 3, ans = 4
67+
68+
1st Iteration:
69+
mid = 1 → arr[1] = 2 < 6 → low = 2
70+
71+
2nd Iteration:
72+
mid = 2 → arr[2] = 4 < 6 → low = 3
73+
74+
3rd Iteration:
75+
mid = 3 → arr[3] = 7 >= 6 → ans = 3, high = 2
76+
77+
Terminate → return ans = 3
78+
79+
Output: 3
80+
```
81+
82+
---
83+
84+
### 3️⃣ Best / Final Optimized Approach
85+
86+
- **Explanation:**
87+
The best solution uses the lower bound logic through binary search. This guarantees both correctness and efficiency.
88+
89+
- **Time Complexity:** O(logN) - Each step cuts the array in half.
90+
- **Space Complexity:** O(1) - No extra data structures used.
91+
92+
- **Example/Dry Run:**
93+
94+
```plaintext
95+
Input: arr[] = [1, 2, 4, 7], x = 2
96+
97+
low = 0, high = 3, ans = 4
98+
99+
1st Iteration:
100+
mid = 1 → arr[1] = 2 >= 2 → ans = 1, high = 0
101+
102+
2nd Iteration:
103+
mid = 0 → arr[0] = 1 < 2 → low = 1
104+
105+
Terminate → return ans = 1
106+
107+
Output: 1
108+
```
109+
110+
---
111+
112+
## 📊 Complexity Analysis
113+
114+
| Approach | Time Complexity | Space Complexity |
115+
| ------------- | --------------- | ---------------- |
116+
| Brute Force | O(N) | O(1) |
117+
| Optimized | O(logN) | O(1) |
118+
| Best Approach | O(logN) | O(1) |
119+
120+
---
121+
122+
## 📉 Optimization Ideas
123+
124+
- The solution is already optimal using binary search.
125+
- In languages like C++ or Python, the `lower_bound()` function from STL or `bisect.bisect_left()` from the `bisect` module can be used directly.
126+
127+
---
128+
129+
## 📌 Example Walkthroughs & Dry Runs
130+
131+
```plaintext
132+
Example 1:
133+
Input: arr[] = [1, 2, 4, 7], x = 6
134+
135+
Step 1 → mid = 1 → arr[1] = 2 < 6 → search right
136+
Step 2 → mid = 2 → arr[2] = 4 < 6 → search right
137+
Step 3 → mid = 3 → arr[3] = 7 >= 6 → candidate → search left
138+
Output: 3
139+
140+
Example 2:
141+
Input: arr[] = [1, 2, 4, 7], x = 2
142+
143+
Step 1 → mid = 1 → arr[1] = 2 == 2 → candidate → search left
144+
Step 2 → mid = 0 → arr[0] = 1 < 2 → search right
145+
Output: 1
146+
```
147+
148+
---
149+
150+
## 🔗 Additional Resources
151+
152+
- [Lower Bound Explained](https://www.geeksforgeeks.org/dsa/lower-and-upper-bound-theory/)
153+
- [Binary Search - GeeksForGeeks](https://www.geeksforgeeks.org/binary-search/)
154+
155+
---
156+
157+
Author: Abdul Wahab
158+
Date: 19/07/2025
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution {
2+
public:
3+
int searchInsert(vector<int>& nums, int target) {
4+
int n = nums.size();
5+
int low = 0, high = n - 1;
6+
int ans = n;
7+
while (low <= high) {
8+
int mid = (low + high) / 2;
9+
if (nums[mid] >= target) {
10+
ans = mid;
11+
high = mid - 1; // look for smaller index on the left
12+
} else {
13+
low = mid + 1; // look on the right
14+
}
15+
}
16+
return ans;
17+
}
18+
};
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
class Solution {
2+
public int searchInsert(int[] nums, int target) {
3+
int n = nums.length;
4+
int low = 0, high = n - 1;
5+
int ans = n;
6+
while (low <= high) {
7+
int mid = (low + high) / 2;
8+
if (nums[mid] >= target) {
9+
ans = mid;
10+
high = mid - 1; // look for smaller index on the left
11+
} else {
12+
low = mid + 1; // look on the right
13+
}
14+
}
15+
return ans;
16+
}
17+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
class Solution:
2+
def searchInsert(self, nums: List[int], target: int) -> int:
3+
n = len(nums)
4+
low = 0
5+
high = n - 1
6+
ans = n
7+
8+
while low <= high:
9+
mid = (low + high) // 2
10+
if nums[mid] >= target:
11+
ans = mid
12+
high = mid - 1 # look for smaller index on the left
13+
else:
14+
low = mid + 1 # look on the right
15+
16+
return ans

0 commit comments

Comments
 (0)