#923

3Sum With Multiplicity

Medium
ArrayHash TableTwo PointersSortingCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n³)
O(n²)
Space
O(1)
O(n)
💡

Intuition

Time O(n²)Space O(n)

The optimal solution uses a combination of sorting and a hash map to efficiently count the occurrences of each number, allowing us to find valid triplets without redundant calculations.

⚙️

Algorithm

5 steps
  1. 1Step 1: Sort the array to enable the use of two pointers.
  2. 2Step 2: Create a frequency map to count occurrences of each number in the array.
  3. 3Step 3: Iterate through each unique number as the first element of the triplet.
  4. 4Step 4: For each pair of subsequent numbers, calculate the required sum and check if it exists in the frequency map.
  5. 5Step 5: Use combinatorial counting to determine how many valid triplets can be formed based on the frequency of the numbers.
solution.py19 lines
1def threeSumMulti(arr, target):
2    from collections import Counter
3    count = 0
4    mod = 10**9 + 7
5    freq = Counter(arr)
6    unique = sorted(freq.keys())
7    for i in range(len(unique)):
8        for j in range(i, len(unique)):
9            k = target - unique[i] - unique[j]
10            if k in freq:
11                if i == j == unique.index(k):
12                    count += freq[unique[i]] * (freq[unique[i]] - 1) * (freq[unique[i]] - 2) // 6
13                elif i == j:
14                    count += freq[unique[i]] * (freq[unique[i]] - 1) // 2 * freq[k]
15                elif j == unique.index(k):
16                    count += freq[unique[j]] * (freq[unique[j]] - 1) // 2 * freq[unique[i]]
17                else:
18                    count += freq[unique[i]] * freq[unique[j]] * freq[k]
19    return count % mod

Complexity note: The time complexity is O(n²) due to the nested loops for unique values, while the space complexity is O(n) for storing the frequency map.

  • 1Using a frequency map helps avoid redundant calculations.
  • 2Sorting the array allows for efficient two-pointer techniques.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.