/35. Search Insert Position

35. Search Insert Position

Easy
Arrays50.8% acceptance

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

Example 1

Input: sorted_sequence = [2, 4, 7, 10], search_value = 8

Output: 3

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

Example 2

Input: sorted_sequence = [0, 5, 9], search_value = 0

Output: 0

Explanation: 0 is found at index 0.

Example 3

Input: sorted_sequence = [-3, 1, 4], search_value = -5

Output: 0

Explanation: -5 should be inserted at index 0.

Example 4

Input: sorted_sequence = [1, 3, 5, 7], search_value = 9

Output: 4

Explanation: 9 should be inserted at index 4.

Constraints

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

Case 1

Input: sorted_sequence = [10, 20, 30, 40], search_value = 25

Expected: 2

Case 2

Input: sorted_sequence = [-10, -5, 0, 5], search_value = -5

Expected: 1

Case 3

Input: sorted_sequence = [1], search_value = 2

Expected: 1

Case 4

Input: sorted_sequence = [1, 2, 3, 4, 5], search_value = 0

Expected: 0

Case 5

Input: sorted_sequence = [100, 200, 300], search_value = 300

Expected: 2