Sort by

recency

|

1243 Discussions

|

  • + 0 comments

    C#

    public static int pairs(int k, List<int> arr)
    {
        var hashSet = new HashSet<int>(arr);
        return hashSet.Count(x => hashSet.Contains(x + k));
    }
    
    
    public static int pairs(int k, List<int> arr)
    {
        var total = 0;
        var hashSet = new HashSet<int>(arr);
    
        foreach (var n in hashSet)
        {
            if (hashSet.Contains(n + k))
            {
                total++;
            }
        }
    
        return total;
    }
    
  • + 0 comments

    Python 3:

    from collections import Counter

    counter = Counter(arr) num_pairs = 0

    for i in arr: if i - k in counter: num_pairs += 1 # Note: integers in arr are distinct

    return num_pairs

  • + 0 comments

    Simple C++ sol using set | O(n)

    `c++

    int pairs(int k, vector arr) { unordered_set st; int n = arr.size(), c = 0; for (int i=0; i

    `

  • + 0 comments

    Nice and easy this time! First time I post a solution here, because I'm stunned it worked at the very first time, wihtout any corrections (rare case;)

    Sort + caterpillar method.

    Java solution:

        public static int pairs(int k, List<Integer> arr) {
            Collections.sort(arr);
            int a = 0;
            int b = 1;
            int count = 0;
            while (a < b && b < arr.size()) {            
                int left = arr.get(a);
                int right = arr.get(b);
                int diff = right - left;
                if (diff == k) {
                    count++;
                    b++;
                } else if (diff > k) {
                    a++;
                    if (a==b) b++;
                } else {
                    b++;
                }            
            }
    				}
            return count;
        }
    
  • + 1 comment

    Python3 Optimal Solution:

    def pairs(k, arr):

    from collections import defaultdict
    arr_elements=set(arr)
    hmap=defaultdict(int)
    
    for i in range(len(arr)):
        if arr[i]+k in arr_elements and (arr[i], arr[i]+k) not in hmap:
            hmap[(arr[i], arr[i]+k)]+=1
    
        if arr[i]-k in arr_elements and (arr[i]-k, arr[i]) not in hmap:
            hmap[(arr[i]-k, arr[i])]+=1
    
    return sum(hmap.values())