Given a 0-indexed integer array nums
, return the number of distinct quadruplets (a, b, c, d)
such that:
nums[a] + nums[b] + nums[c] == nums[d]
, and0 <= a, b, c, d < nums.length
, anda
, b
, c
, and d
are distinct.nums
?
nums
bounded in any specific range?
(-10^6, 10^6)
.(a, b, c, d)
ensuring they are distinct indices.nums[a] + nums[b] + nums[c] == nums[d]
.def countQuadruplets(nums):
n = len(nums)
count = 0
for a in range(n):
for b in range(a+1, n):
for c in range(b+1, n):
for d in range(c+1, n):
if nums[a] + nums[b] + nums[c] == nums[d]:
count += 1
return count
This approach is straightforward but not efficient for larger arrays.
Here is a more optimized approach using a hashmap to store sums of pairs:
def countQuadruplets(nums):
count = 0
n = len(nums)
for i in range(n-3):
sum_map = {}
for j in range(i+1, n-1):
for k in range(j+1, n):
sum_map[nums[i] + nums[j]] = sum_map.get(nums[i] + nums[j], 0) + 1
for l in range(j+1, n):
if nums[l] in sum_map:
count += sum_map[nums[l]]
return count
The brute force approach has a time complexity of (O(n^4)).
The optimized approach reduces this to (O(n^3)):
i
, the inner two loops iterate (O(n^2)) to fill the hashmap and check values.In terms of space complexity:
This optimized approach is more practical for larger inputs while ensuring correctness.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?