35. Search Insert Position

 

Intuition

The problem at hand is to find the position where a target value should be inserted in a sorted array. If the target is already present in the array, we return its index. Otherwise, we return the index where it would be inserted to maintain the sorted order. This is a classic problem that can be efficiently solved using binary search due to the sorted nature of the array.

Approach

  1. Initialization: We start by initializing two pointers, left and right, to the beginning and end of the array, respectively.
  2. Binary Search Loop: We enter a loop that continues as long as left is less than or equal to right.
    • Calculate Midpoint: Compute the midpoint mid of the current subarray.
    • Comparison:
      • If nums[mid] equals the target, we return mid because we’ve found the target.
      • If nums[mid] is greater than the target, we adjust the right pointer to mid - 1 to search in the left half.
      • If nums[mid] is less than the target, we adjust the left pointer to mid + 1 to search in the right half.
  3. Return Insertion Point: If the loop exits without finding the target, left will be at the position where the target should be inserted to maintain the sorted order.

Complexity

  • Time Complexity: The time complexity of this algorithm is (O(\log n)), where (n) is the length of the array. This is because we halve the search space with each iteration of the loop.
  • Space Complexity: The space complexity is (O(1)) since we are using only a constant amount of extra space for the pointers and the midpoint calculation.

This approach ensures that we efficiently find the target or the correct insertion point in a sorted array using binary search. If you have any questions or need further clarification, feel free to ask!

var searchInsert = function(nums, target) { let left = 0; let right = nums.length - 1; while (left <= right) { let mid = Math.floor((left + right) / 2); if (nums[mid] === target) { return mid; } else if (nums[mid] > target) { right = mid - 1; } else { left = mid + 1; } } return left; };

Comments

Popular posts from this blog

3Sum Closest: O(n²) Two-Pointer Magic šŸš€ leetcode: 16

Kadane's Algorithm: Maximum Subarray Problem - LeetCode(53) Solution

14. Longest Common Prefix