Sort by

recency

|

1249 Discussions

|

  • + 0 comments

    C:

    int comp(const void *a, const void *b) {
        return (*(int*)b - *(int*)a);
    }
    
    int pairs(int k, int arr_count, int* arr) {
        int p1 = 0;
        int p2 = 1;
        int count = 0;
        qsort(arr, arr_count, sizeof(int), comp);
        while(p2 < arr_count) {
            long long d = arr[p1] - arr[p2];
            ++p2;
            if(d == k) ++count;
            else if (d > k || p2 >= arr_count) {
                ++p1;
                p2 = p1 + 1;
            }
        }
        return count;
    }
    
  • + 2 comments

    Perl:

    sub pairs {
        my $k = shift;
        my $arr = shift;
        my $res = 0;
    
        my %h = map {$_ => 1} @$arr;
        foreach my $key (keys %h) {
            $res++ if (exists($h{$k + $key}));
        }
    
        return $res;
    }
    
  • + 0 comments

    c++: `

    int pairs(int k, vector<int> arr) {
        int ret = 0;
        set<int> lookup(arr.begin(), arr.end());
        for(auto itr : arr) if(lookup.find(itr + k) != lookup.end()) ret++;
        return ret;
    }
    
  • + 0 comments

    Java:

    public static int pairs(int k, List<Integer> arr) {
        // Create a HashSet for quick lookups
        HashSet<Integer> set = new HashSet<>(arr);
        int numOfpairs = 0;
    
        // Loop through each element in the set
        for (int num : set) {
            // Check if the pair (num + k) exists in the set
            if (set.contains(num - k)) {
                numOfpairs++;
            }
        }
        
        return numOfpairs;
    }
    
  • + 0 comments

    Simple Python Solution:

    def pairs(k, arr):
        arr = set(arr)
        ans = 0
        for i in arr:
            if i + k in arr:
                ans += 1
        return ans