923. 3Sum With Multiplicity

Question

Given an integer array A, and an integer target, return the number of tuples i, j, k such that i < j < k and A[i] + A[j] + A[k] == target.

As the answer can be very large, return it modulo 10^9 + 7.

Example 1:

Input: A = [1,1,2,2,3,3,4,4,5,5], target = 8
Output: 20
Explanation: 
Enumerating by the values (A[i], A[j], A[k]):
(1, 2, 5) occurs 8 times;
(1, 3, 4) occurs 8 times;
(2, 2, 4) occurs 2 times;
(2, 3, 3) occurs 2 times.

Example 2:

Input: A = [1,1,2,2,2,2], target = 5
Output: 12
Explanation: 
A[i] = 1, A[j] = A[k] = 2 occurs 12 times:
We choose one 1 from [1,1] in 2 ways,
and two 2s from [2,2,2,2] in 6 ways.

Note:

  1. 3 <= A.length <= 3000
  2. 0 <= A[i] <= 100
  3. 0 <= target <= 300

Solutions:

  • Method 1: TLE
      class Solution {
          public int threeSumMulti(int[] A, int target) {
              int len = A.length;
              long res = 0;
              Arrays.sort(A); //O(nlgn)
              for(int i = 0; i < len - 2; i++){   //O(nlgn)
                  int t = target - A[i];
                  int slow = i + 1, fast = len - 1;
                  while(slow < fast){
                      int sum = A[slow] + A[fast];
                      if(sum < t){
                          slow++;
                      }else if(sum > t){
                          fast--;
                      }else{
                          //first move the fast pointer.
                          int originalFast = fast;
                          while(slow < fast && A[slow] + A[fast] == t){
                              res++;
                              fast--;
                          }
                          fast = originalFast;
                          slow++;
                      }
                  }
              }
              return (int)(res % (1_000_000_007));
          }
      }
    
  • Method 2: O(n^2 + n)
      class Solution {
          public int threeSumMulti(int[] A, int target) {
              int len = A.length;
              long res = 0L;
              long[] map = new long[101];
              for(int a : A){
                  map[a]++;
              }
              for(int i = 0; i <= 100; i++){
                  for(int j = i; j <= 100; j++){
                      int c = target - i - j;
                      if(c < j || c > 100 || map[i] == 0 || map[j] == 0 || map[c] == 0) continue;
                      if(i == j && j == c) res += (map[i] * (map[i] - 1) * (map[i] - 2) / 6);
                      else if(i == j) res += map[c] * map[i] * (map[i] - 1) / 2;        
                      else if(j == c) res += map[i] * map[j] * (map[j] - 1) / 2;
                      else res += map[i] * map[j] * map[c];
                  }
              }
              return (int)(res % (1_000_000_007));
          }   
      }
    

Reference

  1. 花花酱 LeetCode 923. 3Sum With Multiplicity