Batched Binary Search with Query Caching
Heaps, Sorting & SearchAuto-graded · 19 test casesLast 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^60 <= len(queries) <= 10^5- Values in
arrandqueriesrange from-10^9to10^9. arris 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem requires looking up the first occurrence of multiple target values inside a sorted array arr. We can solve this efficiently by combining two techniques:
-
Lower-Bound Binary Search: Standard binary search stops as soon as
arr[mid] == target. However, to guarantee finding the first instance when duplicates exist, we must continue shrinking the upper bound (hi = mid) wheneverarr[mid] >= target. Using a half-open search range[lo, hi)initialized to[0, len(arr)):- If
arr[mid] < target, setlo = mid + 1(the answer must be to the right). - If
arr[mid] >= target, sethi = mid(the answer could be atmidor to the left).
When
lo == hi,lopoints to the smallest index wherearr[lo] >= target. Iflo < len(arr)andarr[lo] == target, thenlois our answer; otherwise,targetis missing and the answer is-1. - If
-
Memoization (Query Caching): Since
queriesmay contain repeated values, we store every computed lookup in a hash map (cache[value] = result). Subsequent requests for the samevalueare retrieved in $O(1)$ time without re-running the logarithmic binary search. Both successful lookups and missing value results (-1) are cached.
Complexity
- Time Complexity: $O(U \log N + Q)$, where $N$ is the length of
arr, $Q$ is the length ofqueries, and $U$ is the number of unique query values ($U \le Q$). Each unique query triggers one $O(\log N)$ search, and each query takes $O(1)$ time to check and retrieve from the cache. - Space Complexity: $O(U + Q)$ auxiliary space to maintain the hash map cache of size $U$ and build the output array of length $Q$.
Python Reference Solution
from typing import List
def get_first_indices(arr: List[int], queries: List[int]) -> List[int]:
cache = {}
results = []
for value in queries:
if value not in cache:
lo, hi = 0, len(arr)
while lo < hi:
mid = (lo + hi) // 2
if arr[mid] < value:
lo = mid + 1
else:
hi = mid
cache[value] = lo if lo < len(arr) and arr[lo] == value else -1
results.append(cache[value])
return results