Count Increasing Quadruplets — LeetCode 2552 Python Solution
- Problem
- #2552
- Pattern
- Prefix Sum
- Reading time
- 4 min
- Source
- leetcode.com
The problem
Given a 0-indexed integer array nums of size n containing all numbers from 1 to n, return the number of increasing quadruplets. A quadruplet (i, j, k, l) is increasing if: 0 <= i < j < k < l < n, and nums[i] < nums[k] < nums[j] < nums[l].
Example
- Input
- nums = [1,3,2,4,5]
- Output
- 2
- Explanation
- - When i = 0, j = 1, k = 2, and l = 3, nums[i] < nums[k] < nums[j] < nums[l].
Python solution
class Solution:
def countQuadruplets(self, nums: List[int]) -> int:
n = len(nums)
f = [[0] * n for _ in range(n)]
g = [[0] * n for _ in range(n)]
for j in range(1, n - 2):
cnt = sum(nums[l] > nums[j] for l in range(j + 1, n))
for k in range(j + 1, n - 1):
if nums[j] > nums[k]:
f[j][k] = cnt
else:
cnt -= 1
for k in range(2, n - 1):
cnt = sum(nums[i] < nums[k] for i in range(k))
for j in range(k - 1, 0, -1):
if nums[j] > nums[k]:
g[j][k] = cnt
else:
cnt -= 1
return sum(
f[j][k] * g[j][k] for j in range(1, n - 2) for k in range(j + 1, n - 1)
)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n^2) |
| Space | O(n^2) auxiliary |
Pattern: Prefix Sum
Precompute running totals once so any range query becomes a single subtraction. LeetCode 2552. Count Increasing Quadruplets is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.
The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2552. Count Increasing Quadruplets?
- LeetCode 2552. Count Increasing Quadruplets is rated Hard on LeetCode.
- What is the time complexity of LeetCode 2552. Count Increasing Quadruplets?
- The Python solution on this page runs in O(n^2).
- What is the space complexity of LeetCode 2552. Count Increasing Quadruplets?
- The Python solution on this page uses O(n^2) auxiliary space.
- What topics does LeetCode 2552. Count Increasing Quadruplets cover?
- LeetCode 2552. Count Increasing Quadruplets is tagged Binary Indexed Tree, Array, Dynamic Programming, Enumeration and Prefix Sum on LeetCode.