#1995

Count Special Quadruplets

Easy
ArrayHash TableEnumerationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n^4)
O(n^2)
Space
O(1)
O(n)
💡

Intuition

Time O(n^2)Space O(n)

Instead of checking every combination of quadruplets, we can use a hash map to store the sums of pairs of numbers. This allows us to quickly check if the sum of any three numbers equals a fourth number, significantly reducing the number of checks we need to perform.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a hash map to store the frequency of sums of pairs of indices.
  2. 2Step 2: Iterate through the array, and for each index d, check if there exists a sum of two previous indices (a, b) such that nums[a] + nums[b] == nums[d] - nums[c].
  3. 3Step 3: Count valid quadruplets based on the frequency of these sums.
solution.py17 lines
1# Full working Python code
2from collections import defaultdict
3
4def countQuadruplets(nums):
5    count = 0
6    sum_map = defaultdict(int)
7    n = len(nums)
8    for d in range(n):
9        for c in range(d):
10            sum_map[nums[d] - nums[c]] += 1
11        for a in range(d):
12            for b in range(a + 1, d):
13                if nums[a] + nums[b] in sum_map:
14                    count += sum_map[nums[a] + nums[b]]
15    return count
16
17print(countQuadruplets([1, 2, 3, 6]))

Complexity note: The time complexity is O(n^2) because we iterate through pairs of indices to build our hash map and then check sums. The space complexity is O(n) due to the hash map storing sums.

  • 1Using a hash map can significantly reduce the number of checks needed.
  • 2Understanding the relationship between indices and sums is crucial.

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