Sum of Imbalance Numbers of All Subarrays Problem
Description
LeetCode Problem 2763.
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, andsarr[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.
Example 1:
Input: nums = [2,3,1,4]
Output: 3
Explanation: There are 3 subarrays with non-zero imbalance numbers:
- Subarray [3, 1] with an imbalance number of 1.
- Subarray [3, 1, 4] with an imbalance number of 1.
- Subarray [1, 4] with an imbalance number of 1.
The imbalance number of all other subarrays is 0. Hence, the sum of imbalance numbers of all the subarrays of nums is 3.
Example 2:
Input: nums = [1,3,3,3,5]
Output: 8
Explanation: There are 7 subarrays with non-zero imbalance numbers:
- Subarray [1, 3] with an imbalance number of 1.
- Subarray [1, 3, 3] with an imbalance number of 1.
- Subarray [1, 3, 3, 3] with an imbalance number of 1.
- Subarray [1, 3, 3, 3, 5] with an imbalance number of 2.
- Subarray [3, 3, 3, 5] with an imbalance number of 1.
- Subarray [3, 3, 5] with an imbalance number of 1.
- Subarray [3, 5] with an imbalance number of 1.
The imbalance number of all other subarrays is 0. Hence, the sum of imbalance numbers of all the subarrays of nums is 8.
Constraints:
1 <= nums.length <= 10001 <= nums[i] <= nums.length
Solution
Approach: Enumerate Subarrays and Keep a Sorted List
Fix the left end i and extend the right end j one element at a time, keeping the elements seen so far in sorted order and the imbalance cnt of the current subarray.
When nums[j] is inserted, let k be the first position in the sorted list with a value >= nums[j], and h = k - 1 the position just before it:
- If the element at
kexists and exceedsnums[j]by more than 1,cntgrows by 1. - If the element at
hexists and is smaller thannums[j]by more than 1,cntgrows by 1. - If both exist and differ by more than 1, they were already counted as one gap, and
nums[j]now sits between them, socntdrops by 1.
Then insert nums[j] and add cnt to the answer.
Complexity: O(n2 log n) time with a balanced tree (the list-based versions pay O(n) per insertion, which is fine for n <= 1000) and O(n) space.
from bisect import bisect_left
class Solution:
def sumImbalanceNumbers(self, nums: List[int]) -> int:
n = len(nums)
ans = 0
for i in range(n):
sl = []
cnt = 0
for j in range(i, n):
k = bisect_left(sl, nums[j])
h = k - 1
if h >= 0 and nums[j] - sl[h] > 1:
cnt += 1
if k < len(sl) and sl[k] - nums[j] > 1:
cnt += 1
if h >= 0 and k < len(sl) and sl[k] - sl[h] > 1:
cnt -= 1
sl.insert(k, nums[j])
ans += cnt
return ans