Count Special Quadruplets — LeetCode 1995 Python Solution
- Problem
- #1995
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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], and a < b < c < d
This statement is abridged. Read the full problem on LeetCode.
Example
- Input
- nums = [1,2,3,6]
- Output
- 1
- Explanation
- The only quadruplet that satisfies the requirement is (0, 1, 2, 3) because 1 + 2 + 3 == 6.
Python solution
class Solution:
def countQuadruplets(self, nums: List[int]) -> int:
ans, n = 0, len(nums)
for a in range(n - 3):
for b in range(a + 1, n - 2):
for c in range(b + 1, n - 1):
for d in range(c + 1, n):
if nums[a] + nums[b] + nums[c] == nums[d]:
ans += 1
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1995. Count Special Quadruplets is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1995. Count Special Quadruplets?
- LeetCode 1995. Count Special Quadruplets is rated Easy on LeetCode.
- What is the time complexity of LeetCode 1995. Count Special Quadruplets?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1995. Count Special Quadruplets?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1995. Count Special Quadruplets cover?
- LeetCode 1995. Count Special Quadruplets is tagged Array, Hash Table and Enumeration on LeetCode.