Sum of Imbalance Numbers of All Subarrays - Problem

The imbalance number of a 0-indexed integer array arr of length n is defined as the number of indices in sarr = sorted(arr) such that:

  • 0 <= i < n - 1, and
  • sarr[i+1] - sarr[i] > 1

Here, sorted(arr) is the function that returns the sorted version of arr.

Given a 0-indexed integer array nums, return the sum of imbalance numbers of all its subarrays.

A subarray is a contiguous non-empty sequence of elements within an array.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,3,1]
Output: 1
💡 Note: Subarrays: [2]→0, [2,3]→0, [2,3,1]→0, [3]→0, [3,1]→1, [1]→0. Only [3,1] sorted as [1,3] has gap 3-1=2>1, so total is 1.
Example 2 — No Imbalances
$ Input: nums = [1,3,3,3,5]
Output: 8
💡 Note: Multiple subarrays have gaps. For example [1,3] has gap 2, [3,5] has gap 2, [1,3,5] has 2 gaps, etc.
Example 3 — Single Element
$ Input: nums = [1]
Output: 0
💡 Note: Only one subarray [1] with no gaps possible in single element arrays.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • 1 ≤ nums[i] ≤ nums.length

Visualization

Tap to expand
Sum of Imbalance Numbers: [2,3,1]231Input Array[2]: 0 gaps[2,3]: 0 gaps[2,3,1]: 0 gaps[3]: 0 gaps[3,1] → sorted [1,3]: gap 3-1=2>1 → 1 gap[1]: 0 gapsSum: 1
Understanding the Visualization
1
Input
Array [2,3,1] with all possible subarrays
2
Process
Sort each subarray and count gaps > 1
3
Output
Sum of all imbalance numbers
Key Takeaway
🎯 Key Insight: Count gaps > 1 in sorted subarrays and sum across all subarrays
Asked in
Google 15 Microsoft 12
8.9K Views
Medium Frequency
~25 min Avg. Time
234 Likes
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