#2552
Count Increasing Quadruplets
HardArrayDynamic ProgrammingBinary Indexed TreeEnumerationPrefix SumEnumerationPrefix SumDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n^4) | O(n²) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n²)Space O(n)
The optimal solution leverages pre-computation and efficient counting to avoid the nested loops. By fixing j and k, we can count valid i and l indices using prefix sums and suffix counts.
⚙️
Algorithm
3 steps- 1Step 1: Create an array to count how many valid i's exist for each j and k.
- 2Step 2: For each pair (j, k), count valid i's before j and valid l's after k.
- 3Step 3: Sum the products of valid i's and l's for each (j, k) pair to get the total count of quadruplets.
solution.py21 lines
1def countQuadruplets(nums):
2 n = len(nums)
3 count = 0
4 left_count = [0] * n
5 right_count = [0] * n
6
7 for j in range(1, n - 2):
8 for i in range(j):
9 if nums[i] < nums[j]:
10 left_count[j] += 1
11
12 for k in range(n - 2, 1, -1):
13 for l in range(k + 1, n):
14 if nums[k] < nums[l]:
15 right_count[k] += 1
16
17 for j in range(1, n - 2):
18 for k in range(j + 1, n - 1):
19 count += left_count[j] * right_count[k]
20
21 return countℹ
Complexity note: The complexity is O(n²) due to the nested loops for counting valid indices, but the overall number of iterations is significantly reduced compared to the brute-force approach.
- 1Fixing two indices and counting valid combinations for the remaining two can significantly reduce complexity.
- 2Using prefix and suffix counts allows us to efficiently compute valid pairs without redundant checks.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.