Skip to content

2006. Count Number of Pairs With Absolute Difference K 👍

  • Time: $O(n)$
  • Space: $O(100) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  int countKDifference(vector<int>& nums, int k) {
    constexpr int kMax = 100;
    int ans = 0;
    vector<int> count(kMax + 1);

    for (const int num : nums)
      ++count[num];

    for (int i = k + 1; i <= kMax; ++i)
      ans += count[i] * count[i - k];

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public int countKDifference(int[] nums, int k) {
    final int kMax = 100;
    int ans = 0;
    int[] count = new int[kMax + 1];

    for (final int num : nums)
      ++count[num];

    for (int i = k + 1; i <= kMax; ++i)
      ans += count[i] * count[i - k];

    return ans;
  }
}
1
2
3
4
class Solution:
  def countKDifference(self, nums: list[int], k: int) -> int:
    count = collections.Counter(nums)
    return sum(count[i] * count[i - k] for i in range(k + 1, 101))