• + 1 comment

    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;
        }