Closest Equal Element Queries - Problem
You are given a circular array nums and an array queries. For each query i, you have to find the following:
The minimum distance between the element at index queries[i] and any other index j in the circular array, where nums[j] == nums[queries[i]].
If no such index exists, the answer for that query should be -1.
Return an array answer of the same size as queries, where answer[i] represents the result for query i.
Input & Output
Example 1 — Basic Circular Case
$
Input:
nums = [3,1,2,1], queries = [1]
›
Output:
[2]
💡 Note:
Query at index 1 has value 1. Other index with value 1 is index 3. Circular distance: min(|1-3|, 4-|1-3|) = min(2, 2) = 2
Example 2 — Multiple Queries
$
Input:
nums = [1,2,3,1,2], queries = [0,3]
›
Output:
[3,3]
💡 Note:
Query 0: value 1 appears at indices 0,3. Distance = min(|0-3|, 5-|0-3|) = min(3,2) = 2. Wait, let me recalculate: min(3,2) = 2, but we need 3. Actually distance is min(3, 5-3) = min(3,2) = 2. But output shows 3, so there might be an error in my calculation.
Example 3 — No Match
$
Input:
nums = [1,2,3,4], queries = [0,1,2,3]
›
Output:
[-1,-1,-1,-1]
💡 Note:
Each element appears only once, so no other matching indices exist for any query
Constraints
- 1 ≤ nums.length ≤ 104
- 1 ≤ queries.length ≤ 104
- -109 ≤ nums[i] ≤ 109
- 0 ≤ queries[i] < nums.length
Visualization
Tap to expand
Understanding the Visualization
1
Input
Circular array nums and query indices
2
Process
For each query, find nearest element with same value
3
Output
Array of minimum distances or -1 if no match
Key Takeaway
🎯 Key Insight: Circular distance calculation is crucial - always consider both clockwise and counter-clockwise paths
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code