I like to read this solution as a small machine: keep the useful information, throw away the noise. For 1512. Number of Good Pairs, 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 numIdenticalPairs.
Guide
Why?
The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.
- A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
- 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:
- Initialize the memory or helper structure.
- Process candidates in the order the invariant expects.
- Update the answer only when the current state is valid.
- 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
01//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Number of Good Pairs.
02//Memory Usage: 7.2 MB, less than 100.00% of C++ online submissions for Number of Good Pairs.
03class Solution {
04public:
05 int numIdenticalPairs(vector<int>& nums) {
06 map<int, int> counter;
07
08 for(int num : nums){
09 counter[num]++;
10 }
11
12 int ans = 0;
13
14 for(auto it = counter.begin(); it != counter.end(); ++it){
15 if(it->second > 1){
16 ans += it->second * (it->second-1) /2;
17 }
18 }
19
20 return ans;
21 }
22};
Cost