< Back




35. Search Insert Position

Binary search question. Given a target value, find it in the array. If it's not in the array, find
the index where it should be inserted.

The solution is as follows:


  class Solution:
      def searchInsert(self, nums: List[int], target: int) -> int:
          l, r = 0, len(nums) - 1

          while l <= r:
              m = (r + l) // 2

              if nums[m] == target:
                  return m

              if nums[m] < target:
                  l = m + 1
              else:
                  r = m - 1

          return l


_ Time Complexity:

  O(log(n)) - Binary search time complexity.

_ Space Complexity:

  O(1) - We use constant space.