BinarySearch Pre-Idx/Next-Idx
IntuitionApproachComplexity
Time complexity:

Space complexity:
Code
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->

# Approach
<!-- Describe your approach to solving the problem. -->

# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->

- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->

# Code
```csharp []
public class Solution {
    public IList<int> SolveQueries(int[] nums, int[] queries) {
        int len = nums.Length;
        Dictionary<int, List<int>> freq = new();

        for(int i = 0; i < len; i++)
        {
            int cur = nums[i];
            if(!freq.ContainsKey(cur))
                freq.Add(cur, new List<int>());

            freq[cur].Add(i);
        }

        List<int> res = new();
        foreach(int q in queries)
        {
            int key = nums[q];
            List<int> ids = freq[key];

            if(ids.Count == 1)
                res.Add(-1);
            else
            {
                int curId = ids.BinarySearch(q);
                int diff = int.MaxValue, nextId = -1;
                
                // check pre:
                int preId = curId-1;
                if(preId >= 0)
                    diff = ids[curId] - ids[preId];
                else
                    diff = ids[curId] + len - ids.Last();

                // Check next:
                int next = curId+1;
                if(next == ids.Count)
                    diff = Math.Min(diff, len-ids[curId] + ids[0]);
                else
                    diff = Math.Min(diff, ids[next] - ids[curId]);

                res.Add(diff);
            }
        }

        return res;
    }
}
```
['C#']