Simple C++ Approach, Beats 100% in Time and Memory
IntuitionThe idea here is to pass through nums twice and in doing so find the nearest neighbor (as defined by the problem) for each index of the array and store
# Intuition
The idea here is to pass through nums twice and in doing so find the nearest neighbor (as defined by the problem) for each index of the array and store it in `res`.

# Approach
We do this by first passing through and setting the `lastSeen[num]` value to the index of nums for which `num` last appears. Then, we iterate through the array again and update the nearest neighbor of the current index `idx` and the `lastSeen[nums[idx]]` based on the circular distance `diff` between the indices. Finally, grab the selected `query` indices from the resulting `res` array.

# Complexity
- Time complexity:
O(n + q) where `n = nums.size()` and `q = queries.size()`

- Space complexity:
O(n + q) since we create an `n`-length `res` array and a `q`-length `ans` array.

# Code
```cpp []
class Solution {
public:
    vector<int> solveQueries(vector<int>& nums, vector<int>& queries) {
        map<int, int> lastSeen;
        int n = nums.size(), diff = 0, lastIdx = 0;
        vector<int> res(n, -1);
        // first initialize the lastSeen indices
        for (int idx = 0; idx < nums.size(); ++idx) lastSeen[nums[idx]] = idx;
        for (int idx = 0; idx < nums.size(); ++idx) {
            // ensure that more than one index has value nums[idx]
            if (lastSeen[nums[idx]] != idx) {
                lastIdx = lastSeen[nums[idx]];
                // take the difference with the last index
                diff = (idx - lastIdx + n) % n;
                // update the current index's nearest neighbor
                if (res[idx] < 0) {
                    res[idx] = diff;
                } else res[idx] = min(res[idx], diff);
                // update the previous index's nearest neighbor
                if (res[lastIdx] < 0) {
                    res[lastIdx] = diff;
                } else res[lastIdx] = min(res[lastIdx], diff);
                lastSeen[nums[idx]] = idx;
            }
        }
        // grab answers from res specific to query
        vector<int> ans;
        for (int query : queries) {
            ans.push_back(res[query]);
        }
        return ans;
    }
};
```
Please upvote this if you found it helpful!
['C++']