Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created May 25, 2023 21:38
Show Gist options
  • Save Ifihan/1dcd8e427ff7299771f0b086cb649146 to your computer and use it in GitHub Desktop.
Save Ifihan/1dcd8e427ff7299771f0b086cb649146 to your computer and use it in GitHub Desktop.
Search Insert Position

Search Insert Position

Question on Leetcode - Easy

Approach

The approach taken was the binary search to find the target. I initialized two pointers, left and right at the beginning and end of the array respectfully. Then I used a while loop left < right. Then in the loop, I calculate the mid and compare it to the target. If the mid is the target, I return mid. If the mid is less than the target, I add a unit step to the left and if the mid is grater than one, I remove a unit step from the right. If the loop is exited without finding the target, it means the target will be inserted the the left and then I return the left

Code

class Solution:
   def searchInsert(self, nums: List[int], target: int) -> int:
       left, right = 0, len(nums) - 1
       
       while left <= right:
           mid = (left + right) // 2
           
           if nums[mid] == target:
               return mid
           
           if nums[mid] < target:
               left = mid + 1
           else:
               right = mid - 1
       
       return left

Complexities

  • Time Complexity - Olog(n) as explicitly stated in the question
  • Space complexity - O(n)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment