Skip to content

532. K-diff Pairs in an Array

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
 public:
  int findPairs(vector<int>& nums, int k) {
    int ans = 0;
    unordered_map<int, int> numToIndex;

    for (int i = 0; i < nums.size(); ++i)
      numToIndex[nums[i]] = i;

    for (int i = 0; i < nums.size(); ++i) {
      const int target = nums[i] + k;
      if (const auto it = numToIndex.find(target);
          it != numToIndex.cend() && it->second != i) {
        ++ans;
        numToIndex.erase(target);
      }
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public int findPairs(int[] nums, int k) {
    int ans = 0;
    Map<Integer, Integer> numToIndex = new HashMap<>();

    for (int i = 0; i < nums.length; ++i)
      numToIndex.put(nums[i], i);

    for (int i = 0; i < nums.length; ++i) {
      final int target = nums[i] + k;
      if (numToIndex.containsKey(target) && numToIndex.get(target) != i) {
        ++ans;
        numToIndex.remove(target);
      }
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def findPairs(self, nums: list[int], k: int) -> int:
    ans = 0
    numToIndex = {num: i for i, num in enumerate(nums)}

    for i, num in enumerate(nums):
      target = num + k
      if target in numToIndex and numToIndex[target] != i:
        ans += 1
        del numToIndex[target]

    return ans