
Sponsored
Sponsored
The iterative binary search approach involves using two pointers, 'left' and 'right'. We continue dividing the array into halves until we locate the target or determine where it should be inserted. The algorithm compares the target with the middle element and appropriately adjusts the 'left' or 'right' pointer based on this comparison.
Time Complexity: O(log n)
Space Complexity: O(1) since no extra space is used.
1public class SearchInsertPosition {
2 public int searchInsert(int[] nums, int target) {
3 int left = 0, right = nums.length - 1;
4 while (left <= right) {
5 int mid = left + (right - left) / 2;
6 if (nums[mid] == target) return mid;
7 else if (nums[mid] < target) left = mid + 1;
8 else right = mid - 1;
9 }
10 return left;
11 }
12
13 public static void main(String[] args) {
14 SearchInsertPosition sip = new SearchInsertPosition();
15 int[] nums = {1, 3, 5, 6};
16 System.out.println(sip.searchInsert(nums, 5));
17 }
18}
19This Java solution uses a classic binary search to either locate the target or determine where to insert it if it's not present.
In this approach, the binary search is implemented recursively. The function calls itself with updated bounds until the target is found or until it determines the correct insertion index. This approach makes use of stack space due to recursion but is logically intuitive.
Time Complexity: O(log n)
Space Complexity: O(log n) due to recursion stack.
1#
This C solution uses recursion to implement binary search to find the index or the prospective insertion position of the target.