|
| 1 | +package com.cheehwatang.leetcode; |
| 2 | + |
| 3 | +// Time Complexity : O(n), |
| 4 | +// where 'n' is the length of 'arr'. |
| 5 | +// We traverse 'arr' once to count the frequency of the elements. |
| 6 | +// |
| 7 | +// Space Complexity : O(1), |
| 8 | +// as the auxiliary space used is independent of the input 'arr', |
| 9 | +// with the counting array with size of 101 regardless of the input 'arr'. |
| 10 | + |
| 11 | +public class ThreeSumWithMultiplicity_Counting { |
| 12 | + |
| 13 | + // Approach: |
| 14 | + // Using a counting array, get the frequency of all the integers, |
| 15 | + // then check all the possible combinations to get the sum. |
| 16 | + // Note that, i < j < k and arr[i] + arr[j] + arr[k] == target, |
| 17 | + // do not require the index as the sum is not dependent on the index. |
| 18 | + |
| 19 | + public int threeSumMulti(int[] arr, int target) { |
| 20 | + |
| 21 | + // With the constraint of 0 <= arr[i] <= 100, count the frequency of all the integers/ |
| 22 | + int[] counting = new int[101]; |
| 23 | + for (int integer : arr) counting[integer]++; |
| 24 | + |
| 25 | + // Keep the count as long type, so as only need to perform the modulo once at the end. |
| 26 | + long count = 0; |
| 27 | + |
| 28 | + // Traverse the counting array in two for-loops to get the value for 'i' and 'j'. |
| 29 | + for (int i = 0; i <= 100; i++) { |
| 30 | + for (int j = i; j <= 100; j++) { |
| 31 | + // Get the k integer to check if it is in the counting array. |
| 32 | + int k = target - i - j; |
| 33 | + if (k < 0 || k > 100) continue; |
| 34 | + if (counting[k] > 0) { |
| 35 | + // If the triplet is of the same integers (eg. [1,1,1], target = 3), |
| 36 | + // then perform geometric sum for 3 elements. |
| 37 | + if (i == k && j == k) |
| 38 | + count += (long) counting[i] * (counting[i] - 1) * (counting[i] - 2) / 6; |
| 39 | + // If i and j is identical, but different from k (eg. [1,1,2], target = 4), |
| 40 | + // then perform geometric sum for i & j, then multiply with k. |
| 41 | + else if (i == j) |
| 42 | + count += (long) counting[i] * (counting[i] - 1) / 2 * counting[k]; |
| 43 | + // If both i and j is smaller than k, then get the multiples of all the frequency. |
| 44 | + // This is to make sure no duplicates of results |
| 45 | + // (eg, [1,2,3], target = 6), only [1,2,3] is counted, but not [2,1,3] or [3,2,1], etc.) |
| 46 | + else if (i < k && j < k) |
| 47 | + count += (long) counting[i] * counting[j] * counting[k]; |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | + return (int) (count % (1e9 + 7)); |
| 52 | + } |
| 53 | +} |
0 commit comments