KatInterview

Batched Binary Search with Query Caching

Heaps, Sorting & SearchAuto-graded · 19 test cases
MediumAuto-gradedHeaps, Sorting & Searchbinary-searcharraysmemoization

Last updated

Evaluate efficient sorted array lookups for repetitive queries using binary search combined with memoization.

You are given a non-decreasing sorted list of integers arr and a list of query values queries. For each value in queries, find the initial zero-based index of that value in arr. If a value does not exist in arr, the result for that query should be -1.

Because queries may contain many duplicate requests, design your solution to avoid performing redundant binary searches for values that have already been evaluated.

Return a list of integers representing the first index (or -1) for each query in order.

Constraints

  • 0 <= len(arr) <= 10^6
  • 0 <= len(queries) <= 10^5
  • Values in arr and queries range from -10^9 to 10^9.
  • arr is sorted in non-decreasing order.

Examples

Example 1

Input: get_first_indices([1, 2, 2, 2, 3, 4], [2, 5, 2])

Output: [1, -1, 1]

Hints

Hint 1

To find the first occurrence of a target in a sorted array, continue searching the left half even after finding a matching element.

Hint 2

Store search results in a hash map keyed by the query target value so duplicate queries resolve in O(1) time.

Hint 3

Be sure to cache negative outcomes (targets not found) to avoid re-searching missing values.