Repeated Lookups in a Sorted Array
values is sorted in non-decreasing order and may contain duplicates. For each query in queries, return the index of the first occurrence of that value in values, or -1 when it is absent, keeping the queries' order.
Both lists can hold 200,000 entries and queries repeat, so do the work for each distinct value once. Do not modify either input.
locateAll([1, 2, 2, 2, 5], [2, 5, 3, 2]) -> [1, 4, -1, 1] locateAll([], [1, 1]) -> [-1, -1]
Hints
Hint 1
Sorted means the first occurrence of each distinct value is where a run starts; one pass finds them all.
Hint 2
A map from value to first index answers every query in O(1), repeats included; binary search is the fallback when the array is too large to pre-scan.
Topics
Asked at
Sign in to use the assistant — ask what the problem means, get a hint when you're stuck, or have your current work reviewed. Conversations save to your account.