Sum of Imbalance Numbers of All Subarrays - Problem
Imagine you're analyzing the stability of different sections of a data stream. The imbalance number of an array measures how many "gaps" exist when elements are sorted.
Given an array nums, for each possible subarray, we need to:
- Sort the subarray elements
- Count gaps where consecutive sorted elements differ by more than 1
- Sum all these gap counts across all subarrays
For example, in sorted array [1, 3, 7], there are 2 gaps: between 1→3 (diff=2) and 3→7 (diff=4).
Goal: Return the total sum of imbalance numbers for all possible contiguous subarrays.
Input & Output
example_1.py — Basic Case
$
Input:
[2, 3, 1, 4]
›
Output:
6
💡 Note:
All subarrays: [2]=0, [2,3]=0, [2,3,1]=0, [2,3,1,4]=0, [3]=0, [3,1]=1, [3,1,4]=1, [1]=0, [1,4]=1, [4]=0. Subarray [3,1] sorted is [1,3], gap 3-1=2>1, so 1 imbalance. Similarly [3,1,4]→[1,3,4] has gap 3-1=2>1, and [1,4] has gap 4-1=3>1. Total: 1+1+1+3=6.
example_2.py — Sequential Numbers
$
Input:
[1, 3, 3, 3, 5]
›
Output:
8
💡 Note:
Most subarrays containing both 1 and 3 have gap 3-1=2>1 (1 imbalance). Subarrays containing both 3 and 5 have gap 5-3=2>1 (1 imbalance). Duplicates don't create additional gaps in sorted arrays.
example_3.py — Single Element
$
Input:
[1]
›
Output:
0
💡 Note:
Only one subarray [1], which has no consecutive elements, so 0 imbalances.
Visualization
Tap to expand
Understanding the Visualization
1
Identify Gaps
Find where elevation jumps by more than 1 unit
2
Count Efficiently
Use math to avoid generating all combinations
3
Sum Contributions
Add up gap counts from all trail sections
Key Takeaway
🎯 Key Insight: Rather than generating all O(n²) subarrays and sorting each one, we can mathematically calculate how many times each element contributes to imbalances across all possible subarrays, reducing complexity significantly.
Time & Space Complexity
Time Complexity
O(n²)
For each element, we calculate its contribution across all subarrays containing it
⚠ Quadratic Growth
Space Complexity
O(n)
Extra space for tracking element positions and contributions
⚡ Linearithmic Space
Constraints
- 1 ≤ nums.length ≤ 1000
- 1 ≤ nums[i] ≤ nums.length
- All subarrays must be contiguous
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code