Intuition
For each query index q, we need the closest (circular) index with the same
value. Group indices by value; for each query binary-search the group list for
the neighbors of q.
Explanation
Approach
groups = {value: sorted list of indices}.- For each query
q:- Let
arr = groups[nums[q]]. If length1, answer is-1. bisect_left(arr, q)gives the position; the left and right neighbors (wrapping around) are the two candidates.- Minimum of
min(|q - i|, n - |q - i|)for each candidate.
- Let
Implementation
import java.util.*;
class Solution {
public List<Integer> solveQueries(int[] nums, int[] queries) {
int n = nums.length;
Map<Integer, List<Integer>> groups = new HashMap<>();
for (int i = 0; i < n; i++) {
groups.computeIfAbsent(nums[i], k -> new ArrayList<>()).add(i);
}
List<Integer> ans = new ArrayList<>();
for (int q : queries) {
List<Integer> arr = groups.get(nums[q]);
if (arr.size() < 2) {
ans.add(-1);
continue;
}
int k = Collections.binarySearch(arr, q);
int leftIdx = ((k - 1) % arr.size() + arr.size()) % arr.size();
int rightIdx = (k + 1) % arr.size();
int left = arr.get(leftIdx);
int right = arr.get(rightIdx);
int dLeft = Math.abs(q - left);
dLeft = Math.min(dLeft, n - dLeft);
int dRight = Math.abs(q - right);
dRight = Math.min(dRight, n - dRight);
ans.add(Math.min(dLeft, dRight));
}
return ans;
}
}