Algo-Sim › Binary Search
Search Insert Position
Easy · Binary Search · step through it in Java, Python and C++ on your own input
Lower bound with a half-open [lo, hi) range: the first index whose value is ≥ target, which is also where target would be inserted.
Problem
The array nums holds distinct integers in increasing order. Return the index of target if it is present; otherwise return the index where it would be inserted to keep the array sorted. The algorithm must run in O(log n) time.
Constraints
- 1 ≤ nums.length ≤ 10⁴
- -10⁴ ≤ nums[i], target ≤ 10⁴
- nums holds distinct values in increasing order
Edge cases to test
- Target below every value:
0 - Target above every value:
n - Target equal to an existing value
Follow-up questions
- How does this relate to library calls?
- It is
bisect_leftin Python,lower_boundin C++, andArrays.binarySearchwith−(insertion point) − 1in Java. - What changes for the last position instead of the first?
- Use
upper_bound(first value > target) and step back one: the same O(log n) loop with<=in the comparison.
Solution
Java
public int searchInsert(int[] nums, int target) {
int lo = 0, hi = nums.length;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] < target) lo = mid + 1;
else hi = mid;
}
return lo;
}Python
def search_insert(nums, target):
lo, hi = 0, len(nums)
while lo < hi:
mid = lo + (hi - lo) // 2
if nums[mid] < target: lo = mid + 1
else: hi = mid
return loC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int searchInsert(vector<int> &nums, int target) {
int lo = 0, hi = nums.size();
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] < target) lo = mid + 1;
else hi = mid;
}
return lo;
}
};
More Binary Search problems
- Binary Search (Easy)
- Sqrt(x) (Easy)
- Find First and Last Position of Element in Sorted Array (Medium)
- Find Minimum in Rotated Sorted Array (Medium)
- Search in Rotated Sorted Array (Medium)
- Find Peak Element (Medium)
- Single Element in a Sorted Array (Medium)
- Koko Eating Bananas (Medium)
- Kth Smallest Element in a Sorted Matrix (Medium)
- Allocate Minimum Pages (Hard)
- Median of Two Sorted Arrays (Hard)
- Time Based Key-Value Store (Medium)