KatInterview

Find the Slot for a Value in a Sorted List of Distinct Integers

Heaps, Sorting & SearchAuto-graded · 26 test cases
EasyAuto-gradedHeaps, Sorting & Searchbinary-searchsorted-arrayarrays

Last updated

Tests explicit binary search on a sorted array: find a value's index or the position where it would be inserted, in logarithmic time.

You are given a list of integers values sorted in strictly ascending order (all elements are distinct) and a single integer query.

Return the index at which query sits in the list. If query is not in the list, return the index at which it would have to be inserted so that the list stays in ascending order.

Implement the search yourself with an explicit binary search. Do not use bisect or any similar library helper. Your solution should run in O(log n) time.

Output rules

  • If query is present, return its index.
  • If query is absent, return the number of elements that are strictly smaller than query. This is the index where it would be inserted.
  • If query is larger than every element, return len(values).
  • If query is smaller than every element, return 0.
  • If values is empty, return 0.

Constraints

  • 0 <= len(values) <= 10^4
  • -10^4 <= values[i], query <= 10^4
  • values is sorted in strictly ascending order (no duplicates).
  • The returned value is an integer in the range [0, len(values)].

Examples

Example 1

Input: find_insertion_index([1, 3, 5, 6], 5)

Output: 2

Example 2

Input: find_insertion_index([1, 3, 5, 6], 2)

Output: 1

Example 3

Input: find_insertion_index([1, 3, 5, 6], 7)

Output: 4

Example 4

Input: find_insertion_index([1, 3, 5, 6], 0)

Output: 0

Hints

Hint 1

The answer is the first index whose element is greater than or equal to the query, or len(values) if no such element exists.

Hint 2

Keep two pointers, low and high, around the part of the list not yet ruled out. Compare the middle element to the query and discard the half that cannot contain the answer.

Hint 3

When the loop ends without finding the query, every index left of low holds a smaller value and every index from low onward holds a larger value, so low is the insertion index. Do not return high or mid.