Simple JavaScript O(n) using TWO maps


  • 0
    var findPairs = function(nums, k) {
        if (k < 0) return 0;
        const seen = {};
        const pairs = {};
        return nums.reduce((count, a) => {
            count += isNewPair(seen, pairs, a, a - k) + isNewPair(seen, pairs, a, a + k);
            seen[a] = 1;
            return count;
        }, 0);
    };
    
    function isNewPair(seen, pairs, a, b) {
        if (!seen[b]) return false;
        let key = a < b ? a + ',' + b : b + ',' + a;
        if (!pairs[key]) {
            pairs[key] = 1;
            return true;
        }
        return false;
    }
    

    While we could use less space as in the many single-map solutions, this version is IMO easier to reason about.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.