Hashmap + Preproccess answer
Intuition
Group indices by num
Preprocess nearest index values for all indices where num is found
Complexity

Time complexity: O(n+m)


Space complexity: O(n)
# Intuition

-   Group indices by `num`
-   Preprocess nearest index values for all indices where `num` is found

# Complexity

-   Time complexity: $$O(n + m)$$

-   Space complexity: $$O(n)$$

# Code

```python3 []  
n = len(nums)
index_map = defaultdict(list)
for i, num in enumerate(nums):
    index_map[num].append(i)
    
nearest = [-1] * n
for indices in index_map.values():
    if (m := len(indices)) == 1: continue
    for i, index in enumerate(indices):
        next_index = indices[(i+1) % m]
        prev_index = indices[i-1]
        
        if prev_index < index < next_index:
            nearest[index] = min(next_index - index, index - prev_index)
        elif index < prev_index:
            nearest[index] = min(next_index - index, n - prev_index + index)
        else:
            nearest[index] = min(n - index + next_index, index - prev_index)

return [nearest[i] for i in queries]
```

['Python3']