/35. Search Insert Position

35. Search Insert Position

Easy
Arrays50.8% acceptance

Given a sorted array of unique integers in ascending order and an integer value, return the index of the value if it exists in the array. If it does not exist, return the index where it should be inserted to maintain the sorted order. The solution must run in O(log n) time.

Example 1

Input: sorted_array = [2, 4, 7, 10], value = 8

Output: 3

Explanation: 8 should be inserted at index 3 to maintain order.

Example 2

Input: sorted_array = [-5, 0, 3, 9], value = -5

Output: 0

Explanation: -5 is found at index 0.

Example 3

Input: sorted_array = [1, 2, 3, 4], value = 0

Output: 0

Explanation: 0 should be inserted at index 0.

Example 4

Input: sorted_array = [1, 2, 3, 4], value = 5

Output: 4

Explanation: 5 should be inserted at index 4.

Constraints

  • 1 <= len(sorted_array) <= 10_000
  • -10_000 <= sorted_array[i] <= 10_000
  • sorted_array contains unique values sorted in ascending order
  • -10_000 <= value <= 10_000
Python (current runtime)

Case 1

Input: sorted_array = [10, 20, 30, 40], value = 25

Expected: 2

Case 2

Input: sorted_array = [-10, -5, 0, 5], value = -7

Expected: 1

Case 3

Input: sorted_array = [1], value = 1

Expected: 0

Case 4

Input: sorted_array = [1], value = 0

Expected: 0

Case 5

Input: sorted_array = [1], value = 2

Expected: 1