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 of All Subarrays INPUT nums = [2, 3, 1] 2 i=0 3 i=1 1 i=2 All Subarrays: [2] [3] [1] [2,3] [3,1] [2,3,1] Imbalance Definition: Count indices where sorted[i+1] - sorted[i] > 1 in sorted subarray ALGORITHM STEPS 1 Use Set Tracking Track elements in current subarray 2 For Each Subarray Sort and check gaps 3 Count Imbalances Where diff > 1 4 Sum All Counts Return total imbalance Subarray Analysis: [2] sorted:[2] imb:0 [3] sorted:[3] imb:0 [1] sorted:[1] imb:0 [2,3] sorted:[2,3] imb:0 [3,1] sorted:[1,3] imb:1 [2,3,1] sorted:[1,2,3] imb:0 [1,3]: 3-1=2 > 1, so imb=1 FINAL RESULT Sum of all imbalance numbers: 1 Breakdown: 0 + 0 + 0 + 0 + 1 + 0 = 1 Only [3,1] has imbalance sorted: [1,3] gap: 3-1 = 2 > 1 Output: 1 OK Key Insight: Using a Set to track elements allows O(1) insertion and lookup. When adding a new element, we can efficiently check if its neighbors (value +/- 1) exist to update the imbalance count. This avoids re-sorting for each subarray, reducing time complexity significantly. TutorialsPoint - Sum of Imbalance Numbers of All Subarrays | Optimized with Set Tracking
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