Problem Description
Given an array nums which is a permutation of the numbers from 1 to n, count the number of quadruplets (i, j, k, l) with 0 <= i < j < k < l < n satisfying: nums[i] < nums[k] < nums[j] < nums[l].
Key Insights
- The quadruplet condition is not completely monotonic – notice that while indices are in increasing order, the value relationships are interleaved.
- We can fix the middle pair (j, k) with j < k and, provided nums[k] < nums[j], the valid i choices come from indices less than j with nums[i] < nums[k] and the valid l choices come from indices greater than k with nums[l] > nums[j].
- Counting valid i and l efficiently can be achieved using Binary Indexed Trees (Fenwick Trees) for prefix/suffix counting.
- With BITs we can in O(log n) time query the number of elements in a range that satisfy a condition. Iterating over the middle two indices leads to an O(n² log n) solution.
Space and Time Complexity
Time Complexity: O(n² log n), where n is the length of nums. Space Complexity: O(n) for the BIT structures.
Solution
We reframe the problem by fixing indices j and k (with j < k) under the condition that nums[k] < nums[j]. For each such pair, we need: (1) the number of indices i (with i < j) for which nums[i] < nums[k], and (2) the number of indices l (with l > k) for which nums[l] > nums[j]. We pre-process and maintain these counts using two Binary Indexed Trees (BITs). • BIT1 is used for the prefix (indices < j) and is keyed by values (since nums are in 1..n). • BIT2 is used for the suffix (indices > j); for a fixed j, we initially add every index l (from j+1 to n–1) with nums[l] > nums[j] into BIT2. As we iterate k from j+1 onward, we remove the contribution of index k (if it was added) so that BIT2 can answer how many valid l exist with index greater than the current k. We then update our answer by multiplying the count obtained from BIT1 (for i’s) and BIT2 (for l’s) for every valid pair (j, k), and finally update BIT1 by adding nums[j] before moving to the next j.