Skip to content

923. 3Sum With Multiplicity 👍

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
 public:
  int threeSumMulti(vector<int>& arr, int target) {
    constexpr int kMod = 1'000'000'007;
    int ans = 0;
    unordered_map<int, int> count;

    for (const int a : arr)
      ++count[a];

    for (const auto& [i, x] : count)
      for (const auto& [j, y] : count) {
        const int k = target - i - j;
        const auto it = count.find(k);
        if (it == count.cend())
          continue;
        if (i == j && j == k)
          ans = (ans + static_cast<long>(x) * (x - 1) * (x - 2) / 6) % kMod;
        else if (i == j && j != k)
          ans = (ans + static_cast<long>(x) * (x - 1) / 2 * it->second) % kMod;
        else if (i < j && j < k)
          ans = (ans + static_cast<long>(x) * y * it->second) % kMod;
      }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
  public int threeSumMulti(int[] arr, int target) {
    final int kMod = 1_000_000_007;
    int ans = 0;
    Map<Integer, Integer> count = new HashMap<>();

    for (final int a : arr)
      count.merge(a, 1, Integer::sum);

    for (Map.Entry<Integer, Integer> entry : count.entrySet()) {
      final int i = entry.getKey();
      final int x = entry.getValue();
      for (Map.Entry<Integer, Integer> entry2 : count.entrySet()) {
        final int j = entry2.getKey();
        final int y = entry2.getValue();
        final int k = target - i - j;
        if (!count.containsKey(k))
          continue;
        if (i == j && j == k)
          ans = (int) ((ans + (long) x * (x - 1) * (x - 2) / 6) % kMod);
        else if (i == j && j != k)
          ans = (int) ((ans + (long) x * (x - 1) / 2 * count.get(k)) % kMod);
        else if (i < j && j < k)
          ans = (int) ((ans + (long) x * y * count.get(k)) % kMod);
      }
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution:
  def threeSumMulti(self, arr: list[int], target: int) -> int:
    kMod = 1_000_000_007
    ans = 0
    count = collections.Counter(arr)

    for i, x in count.items():
      for j, y in count.items():
        k = target - i - j
        if k not in count:
          continue
        if i == j and j == k:
          ans = (ans + x * (x - 1) * (x - 2) // 6) % kMod
        elif i == j and j != k:
          ans = (ans + x * (x - 1) // 2 * count[k]) % kMod
        elif i < j and j < k:
          ans = (ans + x * y * count[k]) % kMod

    return ans % kMod