Skip to content

Commit b9cc3a6

Browse files
committed
Implement number-of-good-pairs
name: number-of-good-pairs url: https://leetcode.com/problems/number-of-good-pairs difficulty: easy time: 0ms time-rank: 100% time-complexity: O(N) space: 7.5MB space-rank: 94.13% space-complexity: O(1) Fixes #279 Signed-off-by: Christopher Friedt <[email protected]>
1 parent 6875b50 commit b9cc3a6

File tree

2 files changed

+102
-0
lines changed

2 files changed

+102
-0
lines changed

number-of-good-pairs-test.cpp

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/*
2+
* Copyright (c) 2021, Christopher Friedt
3+
*
4+
* SPDX-License-Identifier: MIT
5+
*/
6+
7+
#include <gtest/gtest.h>
8+
9+
#include "number-of-good-pairs.cpp"
10+
11+
using namespace std;
12+
13+
TEST(NumberOfGoodPairs, 1_2_3_1_1_3) {
14+
vector<int> nums = {
15+
1,2,3,1,1,3,
16+
};
17+
EXPECT_EQ(4, Solution().numIdenticalPairs(nums));
18+
}
19+
20+
TEST(NumberOfGoodPairs, 1_1_1_1) {
21+
vector<int> nums = {
22+
1,1,1,1,
23+
};
24+
EXPECT_EQ(6, Solution().numIdenticalPairs(nums));
25+
}
26+
27+
TEST(NumberOfGoodPairs, 1_2_3) {
28+
vector<int> nums = {
29+
1,2,3,
30+
};
31+
EXPECT_EQ(0, Solution().numIdenticalPairs(nums));
32+
}
33+
34+
TEST(NumberOfGoodPairs, 6_5_1_5_7_7_9_1_5_7_1_6_10_9_7_4_1_8_7_1_1_8_6_4_7_4_10_5_3_9_10_1_9_5_5_4_1_7_4_2_9_2_6_6_4_2_10_3_5_3_6_4_7_4_6_4_4_6_3_4_10_1_10_6_10_4_9_6_6_4_8_6_9_5_4) {
35+
vector<int> nums = {
36+
6,5,1,5,7,7,9,1,5,7,1,6,10,9,7,4,1,8,7,1,1,8,6,4,7,4,10,5,3,9,10,1,9,5,5,4,1,7,4,2,9,2,6,6,4,2,10,3,5,3,6,4,7,4,6,4,4,6,3,4,10,1,10,6,10,4,9,6,6,4,8,6,9,5,4
37+
};
38+
EXPECT_EQ(303, Solution().numIdenticalPairs(nums));
39+
}

number-of-good-pairs.cpp

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/*
2+
* Copyright (c) 2021, Christopher Friedt
3+
*
4+
* SPDX-License-Identifier: MIT
5+
*/
6+
7+
#include <sstream>
8+
9+
#include <unordered_map>
10+
#include <vector>
11+
12+
using namespace std;
13+
14+
// name: number-of-good-pairs
15+
// url: https://leetcode.com/problems/number-of-good-pairs
16+
// difficulty: 1
17+
18+
static int choose(int n, int k) {
19+
20+
// C(n, k) := n! / (k!*(n - k)!)
21+
// := n(n-1)(n-2)..(n-k+1)/(k(k-1)(k-2)..1)
22+
// C(n, k) == C(n, k - n) (binomial theorem)
23+
if (n - k < k) {
24+
k = n - k;
25+
}
26+
27+
int val = 1;
28+
29+
for(int i = 0; i < k; ++i) {
30+
val *= (n - i);
31+
val /= (i + 1);
32+
}
33+
34+
return val;
35+
}
36+
37+
class Solution {
38+
public:
39+
int numIdenticalPairs(vector<int>& nums) {
40+
array<int,101> hist;
41+
hist.fill(0);
42+
array<int,101> dp;
43+
dp.fill(0);
44+
45+
// O(N)
46+
for(auto& n: nums) {
47+
hist[n]++;
48+
}
49+
50+
int r = 0;
51+
for(const auto& n: hist) {
52+
if (n >= 2) {
53+
if (dp[n] == 0) {
54+
dp[n] = choose(n, 2);
55+
}
56+
r += dp[n];
57+
}
58+
}
59+
60+
return r;
61+
}
62+
};
63+

0 commit comments

Comments
 (0)