Skip to content

Commit cdb792c

Browse files
committed
Add solution #923
1 parent 00bfcf2 commit cdb792c

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -732,6 +732,7 @@
732732
920|[Number of Music Playlists](./solutions/0920-number-of-music-playlists.js)|Hard|
733733
921|[Minimum Add to Make Parentheses Valid](./solutions/0921-minimum-add-to-make-parentheses-valid.js)|Medium|
734734
922|[Sort Array By Parity II](./solutions/0922-sort-array-by-parity-ii.js)|Easy|
735+
923|[3Sum With Multiplicity](./solutions/0923-3sum-with-multiplicity.js)|Medium|
735736
925|[Long Pressed Name](./solutions/0925-long-pressed-name.js)|Easy|
736737
926|[Flip String to Monotone Increasing](./solutions/0926-flip-string-to-monotone-increasing.js)|Medium|
737738
929|[Unique Email Addresses](./solutions/0929-unique-email-addresses.js)|Easy|
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/**
2+
* 923. 3Sum With Multiplicity
3+
* https://leetcode.com/problems/3sum-with-multiplicity/
4+
* Difficulty: Medium
5+
*
6+
* Given an integer array arr, and an integer target, return the number of tuples i, j, k such
7+
* that i < j < k and arr[i] + arr[j] + arr[k] == target.
8+
*
9+
* As the answer can be very large, return it modulo 109 + 7.
10+
*/
11+
12+
/**
13+
* @param {number[]} arr
14+
* @param {number} target
15+
* @return {number}
16+
*/
17+
var threeSumMulti = function(arr, target) {
18+
const MOD = 1e9 + 7;
19+
const counts = new Map();
20+
let result = 0;
21+
22+
for (const num of arr) {
23+
counts.set(num, (counts.get(num) || 0) + 1);
24+
}
25+
26+
const uniqueNums = [...counts.keys()].sort((a, b) => a - b);
27+
28+
for (let i = 0; i < uniqueNums.length; i++) {
29+
const num1 = uniqueNums[i];
30+
for (let j = i; j < uniqueNums.length; j++) {
31+
const num2 = uniqueNums[j];
32+
const num3 = target - num1 - num2;
33+
34+
if (num3 < num2) continue;
35+
36+
const count1 = counts.get(num1);
37+
const count2 = counts.get(num2);
38+
const count3 = counts.get(num3) || 0;
39+
40+
if (num1 === num2 && num2 === num3) {
41+
result = (result + (count1 * (count1 - 1) * (count1 - 2)) / 6) % MOD;
42+
} else if (num1 === num2) {
43+
result = (result + (count1 * (count1 - 1) * count3) / 2) % MOD;
44+
} else if (num2 === num3) {
45+
result = (result + (count1 * count2 * (count2 - 1)) / 2) % MOD;
46+
} else {
47+
result = (result + count1 * count2 * count3) % MOD;
48+
}
49+
}
50+
}
51+
52+
return result;
53+
};

0 commit comments

Comments
 (0)