Sort by

recency

|

1265 Discussions

|

  • + 0 comments
    int pairs(int k, vector<int> arr) {
        sort(arr.begin(),arr.end());
        set<int> arrset;
        int pairs = 0;
        
        for(int n : arr){
            if(arrset.count(n+k)||arrset.count(n-k)){
                pairs++;
            }
            arrset.insert(n);
        }
        
        return pairs;
    }
    
  • + 0 comments
    def pairs(k, arr):
        s1 = set(arr)
        s2 = set(i + k for i in s1)
        return len(s1 & s2)
    
  • + 0 comments

    java public static int pairs(int k, List arr) { int count = 0; int start = 0; Collections.sort(arr); for(int i = 1; i < arr.size(); i++){ int diff = arr.get(i) - arr.get(start); if(diff > k) { start++; i--; } else if (diff == k) { count++; start++; } } return count; }

  • + 0 comments

    Java solution using Lambdas

    public static int pairs(int k, List<Integer> arr) {
        // Write your code here
        Set<Integer> complementSet = ConcurrentHashMap.newKeySet();
        arr.stream().forEach(f -> complementSet.add(f));
        return (int) arr.parallelStream().filter(d -> complementSet.contains(k + d)).count();
    }
    

    }

  • + 0 comments

    Golang Time Complexity: O(n) Space Complexity: O(n)

    First: populates a hash map with all elements from the input array arr for quick lookups.

    Second: For each element x, it checks if x - k and x + k exist in the hash map. if exist, count

    The current element x is then removed from the hash map to prevent counting the same pair twice (e.g., counting (3, 5) when x=3 and then again when x=5)

    func pairs(k int32, arr []int32) int32 {
    exist := make(map[int32]bool)
    for _, x := range arr {
        exist[x] = true
    }
    
    count := int32(0)
    for _, x := range arr {
        if exist[x-k] {
            count++
        }
        if exist[x+k] {
            count++
        }
        exist[x] = false
    }
    return count
    

    }

    `