Count Increasing Quadruplets - 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]

Notice the specific ordering pattern: element at position k comes between elements at positions i and j in value, creating a unique increasing subsequence pattern.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,3,2,4,5]
Output: 2
💡 Note: Two valid quadruplets: (0,1,2,3) where 1<2<3<4, and (0,1,2,4) where 1<2<3<5. Both follow the pattern nums[i]
Example 2 — No Valid Quadruplets
$ Input: nums = [4,3,2,1]
Output: 0
💡 Note: Array is decreasing, so no quadruplet can satisfy the increasing condition nums[i] < nums[k] < nums[j] < nums[l].
Example 3 — Complex Pattern
$ Input: nums = [4,1,5,2,6,3]
Output: 3
💡 Note: Valid quadruplets: (1,2,3,4) gives 1<2<5<6, (1,2,5,4) gives 1<3<5<6, and (1,4,5,2) gives 1<3<6

Constraints

  • 4 ≤ nums.length ≤ 4000
  • 1 ≤ nums[i] ≤ nums.length
  • All values in nums are unique
  • nums contains all integers from 1 to n

Visualization

Tap to expand
Count Increasing Quadruplets INPUT nums array (indices 0-4) 1 i=0 3 i=1 2 i=2 4 i=3 5 i=4 Quadruplet Condition: i < j < k < l nums[i] < nums[k] < nums[j] < nums[l] Note: Not strictly increasing! nums[k] < nums[j] (swapped) nums = [1,3,2,4,5] n = 5 ALGORITHM STEPS 1 Fix middle pair (j,k) Try all j < k combinations 2 Check nums[k] < nums[j] Only valid if k-value smaller 3 Count valid i (left) nums[i] < nums[k], i < j 4 Count valid l (right) nums[l] > nums[j], l > k Valid Quadruplets Found: (0,1,2,3): 1<2<3<4 OK (0,1,2,4): 1<2<3<5 OK (0,1,3,4): 1<4<3<5 FAIL result += count_i * count_l for each valid (j,k) pair FINAL RESULT Quadruplet 1: (0,1,2,3) 1 3 2 4 5 1 < 2 < 3 < 4 Quadruplet 2: (0,1,2,4) 1 3 2 4 5 1 < 2 < 3 < 5 i pos j pos k pos l pos OUTPUT 2 2 increasing quadruplets found in the array Key Insight: Fix the middle elements j and k, then count valid i's on the left (nums[i] < nums[k]) and valid l's on the right (nums[l] > nums[j]). The key constraint is nums[k] < nums[j] - the values at k and j are "inverted". Use prefix counts and suffix counts to achieve O(n^2) complexity instead of brute-force O(n^4). TutorialsPoint - Count Increasing Quadruplets | Fix Middle Elements (j,k) Approach
Asked in
Google 15 Facebook 12 Amazon 8
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending

Select Compiler

Choose a programming language

Compiler list would appear here...