Count Increasing Quadruplets Problem
#2552
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2552.
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, andnums[i] < nums[k] < nums[j] < nums[l].
Example 1:
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].
- When i = 0, j = 1, k = 2, and l = 4, nums[i] < nums[k] < nums[j] < nums[l].
There are no other quadruplets, so we return 2.
Example 2:
Input: nums = [1,2,3,4]
Output: 0
Explanation: There exists only one quadruplet with i = 0, j = 1, k = 2, l = 3, but since nums[j] < nums[k], we return 0.
Constraints:
4 <= nums.length <= 40001 <= nums[i] <= nums.length- All the integers of
numsare unique.numsis a permutation.
Solution
Approach: Enumerate the Middle Pair
Fix the two middle indices j < k with nums[j] > nums[k]. A valid quadruplet then needs an i < j with nums[i] < nums[k] and an l > k with nums[l] > nums[j]. The two choices are independent, so the number of quadruplets for this (j, k) is the product of their counts.
Precompute both counts for all pairs:
f[j][k]: the number ofl > kwithnums[l] > nums[j]. For a fixedj, start with the count over alll > jand decrease it askmoves right past elements greater thannums[j].g[j][k]: the number ofi < jwithnums[i] < nums[k], built the same way for a fixedkwhilejmoves left.
The answer is the sum of f[j][k] * g[j][k] over all pairs with nums[j] > nums[k].
Complexity: O(n2) time and O(n2) extra space.
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)
)