35. Search Insert Position
Intuition
Complexity
Space Complexity
Time Complexity
Code
public int searchInsert(int[] nums, int target) {
// Initialize binary search boundaries
int left = 0, right = nums.length - 1;
// Perform binary search
while (left <= right) {
int mid = (left + right) >> 1; // Same as (left + right) / 2
// If target found at mid, return index
if (nums[mid] == target) return mid;
// If target is greater, discard left half
if (nums[mid] < target) {
left = mid + 1;
}
// If target is smaller, discard right half
else {
right = mid - 1;
}
}
// If not found, left is the correct insertion index
return left;
}
Last updated