Sort by

recency

|

1242 Discussions

|

  • + 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())
    
  • + 0 comments

    My idea is loop the array and plus earch number at index with K then push the result to Collections array. Next step I will check the element in Collections exist in arr and counting that.

    With c#

    public static int pairs(int k, List<int> arr)
        {
            var collections = arr.Select(number => k + number);
            var numberExisted = collections.Where(number => arr.Contains(number)).ToList();
            
            return numberExisted.Count();
        }