JS Solution (HashMap and BinarySearch)
IntuitionApproachComplexity
Time complexity: O(N+MlogN)

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

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

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

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

# Code
```javascript []
/**
 * @param {number[]} nums
 * @param {number[]} queries
 * @return {number[]}
 */
var solveQueries = function(nums, queries) {
    const numsMap = new Map();
    for(let i = 0; i < nums.length; i++) {
        if(!numsMap.has(nums[i]))
            numsMap.set(nums[i], []);
        numsMap.get(nums[i]).push(i);
    }
    let res = [];
    for(const query of queries) {
        const validIdx = query;
        const targets = numsMap.get(nums[validIdx]);
        const pivot = binarySearch(targets, validIdx);
        let minDist = Math.min(
                dist(targets[pivot + 1], validIdx),
                dist(targets[pivot - 1], validIdx),
                dist(targets[0], validIdx),
                dist(targets[targets.length - 1], validIdx)
            );
        if(minDist === Infinity)
            res.push(-1)
        else
            res.push(minDist)
    }

    function dist(i, j) {
        if(i === undefined || j === -1 || i === j)
            return Infinity;
        const forwardDist = Math.abs(i - j)
        const dist = Math.min(forwardDist, nums.length - forwardDist)
        return dist;
    }
    return res;
};

function binarySearch(arr, target) {
    let left = 0;
    let right = arr.length - 1;

    while (left <= right) {
        let mid = Math.floor((left + right) / 2);

        if (arr[mid] === target) {
            return mid; // Target found, return index
        } else if (arr[mid] < target) {
            left = mid + 1; // Search right half
        } else {
            right = mid - 1; // Search left half
        }
    }

    return -1; // Target not found
}
```
['JavaScript']