AlgoMaster Logo

Search Insert Position

Ashish

Ashish Pratap Singh

easy

Problem Description

Solve it on LeetCode

Approaches

Intuition:

A straightforward approach to solve this problem is to go through the array and find the target or the position where it can be inserted in order. This is done by iterating over the array and checking each element against the target.

Steps:

  1. Iterate through each element in the array.
  2. If the current element is equal to the target, return its index.
  3. If the current element is greater than the target, return the current index since that is where the target should be inserted.
  4. If the loop completes without finding a position, it means the target is larger than all elements, so return the length of the array as the insertion point.

Code:

Intuition:

Since the array is sorted, we can use binary search to find the position for the target more efficiently. Binary search involves dividing the problem space in half during each iteration, making it much faster than a linear search.

Steps:

  1. Initialize two pointers: left at the start and right at the end of the array.
  2. While left is less than or equal to right:
    • Calculate mid as the average of left and right (careful for overflows by using left + (right - left) / 2).
    • If nums[mid] is equal to the target, return mid.
    • If nums[mid] is less than the target, move left to mid + 1.
    • If nums[mid] is greater than the target, move right to mid - 1.
  3. If we didn't find the target, left will be the position where the target should be inserted.

Code: