← Home

532. K-diff Pairs in an Array

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
straightforward implementationC++Markdown
532

I like to read this solution as a small machine: keep the useful information, throw away the noise. For 532. K-diff Pairs in an Array, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: straightforward implementation.

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are findPairs.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
  • A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
  • A set is doing the membership or uniqueness work, which keeps the main loop readable.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 28 ms, faster than 95.45% of C++ online submissions for K-diff Pairs in an Array.
02//Memory Usage: 13.4 MB, less than 83.07% of C++ online submissions for K-diff Pairs in an Array.
03class Solution {
04public:
05    struct pair_hash_int {
06        inline std::size_t operator()(const std::pair<int,int> & v) const {
07            return v.first*31+v.second;
08        }
09    };
10    
11    int findPairs(vector<int>& nums, int k) {
12        int n = nums.size();
13        
14        unordered_set<pair<int, int>, pair_hash_int> pairs;
15        
16        sort(nums.begin(), nums.end());
17        
18        // for(const int& num : nums){
19        //     cout << num << " ";
20        // }
21        // cout << endl;
22        
23        for(int i = 0, j = 1; i < n && j < n; ){
24            // cout << i << ", " << j << endl;
25            if(nums[j] - nums[i] == k){
26                // cout << "insert" << endl;
27                pairs.insert({nums[i], nums[j]});
28                ++i, ++j;
29            }else if(nums[j] - nums[i] < k){
30                ++j;
31            }else{
32                ++i;
33                //j cannot be same as i
34                if(j == i) ++j;
35            }
36        }
37        
38        return pairs.size();
39    }
40};
41
42//counter
43//https://leetcode.com/problems/k-diff-pairs-in-an-array/discuss/100098/Java-O(n)-solution-one-Hashmap-easy-to-understand
44//Runtime: 40 ms, faster than 75.08% of C++ online submissions for K-diff Pairs in an Array.
45//Memory Usage: 14.1 MB, less than 48.00% of C++ online submissions for K-diff Pairs in an Array.
46class Solution {
47public:
48    int findPairs(vector<int>& nums, int k) {
49        map<int, int> counter;
50        
51        for(const int& num : nums){
52            ++counter[num];
53        }
54        
55        int ans = 0;
56        
57        //the key is sorted
58        for(const pair<int, int>& p : counter){
59            if(k == 0){
60                if(p.second >= 2) ++ans;
61            }else{
62                //since key is sorted, we only need to find in one direction
63                if(counter.find(p.first+k) != counter.end()){
64                    ++ans;
65                }
66            }
67        }
68        
69        return ans;
70    }
71};
72
73//counter, one pass
74//https://leetcode.com/problems/k-diff-pairs-in-an-array/discuss/100098/Java-O(n)-solution-one-Hashmap-easy-to-understand/146186
75//Runtime: 32 ms, faster than 91.00% of C++ online submissions for K-diff Pairs in an Array.
76//Memory Usage: 13.6 MB, less than 62.63% of C++ online submissions for K-diff Pairs in an Array.
77class Solution {
78public:
79    int findPairs(vector<int>& nums, int k) {
80        unordered_map<int, int> counter;
81        
82        int ans = 0;
83        
84        for(const int& num : nums){
85            if(counter.find(num) == counter.end()){
86                if(counter.find(num-k) != counter.end()) ++ans;
87                if(counter.find(num+k) != counter.end()) ++ans;
88            }else if(counter[num] == 1){
89                if(k == 0) ++ans;
90            }
91            ++counter[num];
92        }
93        
94        return ans;
95    }
96};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.