Binary Search solution:  TC: O(N+QLogN)
Code


# Code
```cpp []

//TC: O(N+QLogN)
class Solution {
public:
    vector<int> solveQueries(vector<int>& nums, vector<int>& queries) {
        vector<int> ans;
        int size = nums.size();
        map<int, vector<int>> mp;

        // Store indices of each element in the map
        for (int i = 0; i < size; i++) {
            mp[nums[i]].push_back(i);
        }

        for (int i = 0; i < queries.size(); i++) {
            int ind = queries[i];
            int ele = nums[ind];
            int vecsize = mp[ele].size();

            if (vecsize == 1) {
                ans.push_back(-1);  // If only one occurrence, return -1
                continue;
            }

            //Binary Search to find ind in mp[ele]
            int low = 0, high = vecsize - 1, j = -1;
            while (low <= high) {
                int mid = low + (high - low) / 2;
                if (mp[ele][mid] == ind) {
                    j = mid; // Found the index position
                    break;
                } else if (mp[ele][mid] > ind) {
                    high = mid - 1;
                } else {
                    low = mid + 1;
                }
            }


            int left = INT_MAX, right = INT_MAX;

            //1
            if (j > 0 && j < vecsize - 1) {
                left = min(left, ind - mp[ele][j - 1]);
                right = min(right, mp[ele][j + 1] - ind);
            } 

            //2
            else if (j == 0 && j < vecsize - 1) {
                left = min(left, (mp[ele][j] + 1) + (size - 1 - mp[ele][vecsize - 1]));
                right = min(right, mp[ele][j + 1] - ind);
            } 

            //3
            else if (j > 0 && j == vecsize - 1) {
                left = min(left, ind - mp[ele][j - 1]);
                right = min(right, (size - 1 - mp[ele][j]) + (mp[ele][0] + 1));
            }

            ans.push_back(min(left, right));
        }

        return ans;
    }
};

```
['C++']