Sum of Imbalance Numbers of All Subarrays — LeetCode 2763 Python Solution

HardArrayHash TableEnumeration
Problem
#2763
Pattern
Hash Map
Reading time
4 min

The 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.

Example

Input
nums = [2,3,1,4]
Output
3
Explanation
There are 3 subarrays with non-zero imbalance numbers:

Python solution

Python
class Solution:
    def sumImbalanceNumbers(self, nums: List[int]) -> int:
        n = len(nums)
        ans = 0
        for i in range(n):
            sl = SortedList()
            cnt = 0
            for j in range(i, n):
                k = sl.bisect_left(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.add(nums[j])
                ans += cnt
        return ans

Complexity

MeasureComplexity
TimeO(n^2 \times \log n)
SpaceO(n), where n is the length of the array nums auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2763. Sum of Imbalance Numbers of All Subarrays is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2763. Sum of Imbalance Numbers of All Subarrays?
LeetCode 2763. Sum of Imbalance Numbers of All Subarrays is rated Hard on LeetCode.
What is the time complexity of LeetCode 2763. Sum of Imbalance Numbers of All Subarrays?
The Python solution on this page runs in O(n^2 \times \log n).
What is the space complexity of LeetCode 2763. Sum of Imbalance Numbers of All Subarrays?
The Python solution on this page uses O(n), where n is the length of the array nums auxiliary space.
What topics does LeetCode 2763. Sum of Imbalance Numbers of All Subarrays cover?
LeetCode 2763. Sum of Imbalance Numbers of All Subarrays is tagged Array, Hash Table and Enumeration on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview