Problem Description
Given a circular array called nums and a list of queries, for each query index, find the minimum circular distance from the queried index to any other index with the same value. If no such index exists, return -1 for that query.
Key Insights
- Preprocess the input array to map each value to the list of all indices where that value occurs.
- Since the array is circular, the distance between two indices requires considering wrapping around the end of the array.
- Use binary search on each sorted list of indices when processing a query to quickly find the nearest indices with the same value.
- Consider both the right (or forward) and left (or backward) neighbors and compute the appropriate circular distances.
Space and Time Complexity
Time Complexity: O(n + q * log(n))
Space Complexity: O(n)
Solution
To solve the problem efficiently:
- Traverse the nums array once to build a dictionary mapping each unique value to a sorted list of its indices.
- For each query, retrieve the list of indices for the target value.
- If the list contains just one element, return -1.
- Use binary search to determine the position of the queried index within the list.
- Identify the potential nearest neighbor indices (one immediately before and one immediately after the queried index in the circular sense).
- Calculate the circular distances by taking into account the possibility of wrapping around the array boundaries.
- Return the minimum of these distances.
The main trick is handling the circular nature by also checking the wrap-around candidate (i.e., the difference between the queried index and the first or last index in the list, considering the circular gap).