Answer Repeated Lookup Queries Efficiently
SnowflakeSoftware Engineer · Technical ScreenLast updated
This problem tests binary search proficiency and the ability to optimize performance for repetitive computational tasks using memoization.
Problem: Batched Sorted Lookups
You are given a sorted array arr of integers and a list of queries. Your task is to return the first index of each queried value in arr. If a value is not found, return -1. Since the query list may contain duplicate values, your implementation should optimize redundant searches.
Function Signature
def get_first_indices(arr: List[int], queries: List[int]) -> List[int]:
Constraints
1 <= len(arr) <= 10^61 <= len(queries) <= 10^5- Values in
arrandqueriesare within the range[-10^9, 10^9]
Examples
Example 1:
Input: arr = [1, 2, 2, 2, 3, 4], queries = [2, 5, 2]
Output: [1, -1, 1]
Explanation: The first occurrence of 2 is at index 1. 5 is not in the array. The second query for 2 retrieves the cached result from the first query.
Edge Cases
arris empty orqueriesis empty.- All values in
arrare identical. - All queried values are absent from
arr. - Large number of duplicate queries (e.g., millions of identical queries).
Requirements
- You must implement a binary search algorithm to find the first index.
- Use a cache to store the result of values previously searched to avoid re-calculating the same search.
Hints
Hint 1
To find the first occurrence of a value in a sorted array, use a modified binary search that continues searching to the left even after finding the target value.
Hint 2
Python's `bisect_left` module provides an efficient way to find the insertion point, which corresponds to the first index of the value if it exists.
Hint 3
Use a hash map (dictionary) to store the result of each unique query so that subsequent identical lookups take O(1) time.
Follow-up questions
- How would your approach change if the `arr` was updated dynamically between batches of queries?
- What is the total time complexity of your solution, considering both the initial binary searches and the caching mechanism?
- If the memory usage of your cache becomes an issue, what eviction strategy would you implement and why?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.