O(n) solution using triple aaa trick
For each value, store a list of the indices where it occurs. Then when you can scan through the each lists of indices, the closest occurrences are your adjacent
For each value, store a list of the indices where it occurs. Then when you can scan through the each lists of indices, the closest occurrences are your adjacent neighbors. However, instead of doing this on the original array `a`, use the triple concatenated array `aaa` and check results for `j` where `n <= j < 2n`. This allows us to avoid using modular indexing. We also don't need to do any out-of-bounds checking, since we will see `a[j]` n indices to the left and another `a[j]` n indices to the right.


# Complexity
- Time complexity: $$O(n)$$
- Space complexity: $$O(n)$$

# Code
```python3 []
class Solution:
    def solveQueries(self, a: List[int], queries: List[int]) -> List[int]:
        n = len(a)
        N = 2 * len(a)

        aaa = a+a+a

        # val -> sorted indices where val occurs
        occurrences = defaultdict(list)

        for i,x in enumerate(aaa):
            occurrences[x].append(i)
        
        ret = [-1] * n

        for xoccurrences in occurrences.values():
            for i,j,k in zip(xoccurrences, xoccurrences[1:], xoccurrences[2:]):
                if n <= j < N:
                    left = j-i
                    right = k-j

                    if left != n:
                        ret[j-n] = left if left <= right else right
        
        query_ret = [ret[i] for i in queries]
        return query_ret

```
['Python3']