We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Sum of Imbalance Numbers of All Subarrays

Number: 2849

Difficulty: Hard

Paid? No

Companies: Adobe, Google


Problem Description

Given a 0-indexed integer array nums, the imbalance number of an array is defined as follows. First, sort the array and then count the number of indices i (with 0 ≤ i < n-1) where the difference between consecutive numbers is strictly greater than 1. For every non-empty contiguous subarray of nums, determine its imbalance number (calculated on the sorted version of the subarray) and return the sum of these imbalance numbers over all subarrays.


Key Insights

  • The imbalance number for a subarray equals the count of “gaps” between consecutive distinct elements where the gap is larger than 1.
  • A brute-force method involves iterating over all subarrays (O(n²)) and, for each, collecting its distinct elements in sorted order to compute the imbalance count.
  • To speed up insertion into (or maintenance of) the sorted order of distinct elements, binary search can be used. This reduces the overhead per subarray update.
  • More advanced techniques (such as contribution tricks or segment trees) exist to avoid re-computation from scratch for each subarray, but the described approach is sufficient when n is at most 1000.

Space and Time Complexity

Time Complexity: O(n² · log(n)) on average, due to iterating over all subarrays and inserting distinct numbers into a sorted list using binary search. Space Complexity: O(n), used for storing frequency counts and the sorted list of distinct numbers for each subarray.


Solution

The solution iterates through each possible subarray by fixing a starting index and then extending the end index. For each subarray, we maintain:

  • A frequency map to count occurrences of each number.
  • A sorted list of distinct numbers for the current subarray (maintained using binary search insertion).

When a new number is encountered (its frequency goes from 0 to 1), it is inserted into the sorted list at its proper position. Then, we compute the imbalance number by checking adjacent pairs in this sorted list and incrementing the count when the difference is greater than one. Finally, the imbalance for this subarray is added to the total sum. This method leverages efficient update of the subarray’s distinct sorted values and avoids recomputation from scratch each time.


Code Solutions

import bisect

def sumImbalanceNumbers(nums):
    n = len(nums)
    total_imbalance = 0
    # iterate over all possible starting indices
    for start in range(n):
        freq = {}
        distinct_sorted = []  # maintain sorted distinct elements for current subarray
        # extend subarray one element at a time
        for end in range(start, n):
            num = nums[end]
            freq[num] = freq.get(num, 0) + 1
            # if first occurrence, insert in sorted order using bisect
            if freq[num] == 1:
                bisect.insort(distinct_sorted, num)
            # compute imbalance: count gaps in adjacent distinct numbers > 1
            imbalance = 0
            for i in range(len(distinct_sorted) - 1):
                if distinct_sorted[i+1] - distinct_sorted[i] > 1:
                    imbalance += 1
            total_imbalance += imbalance
    return total_imbalance

# Example usage:
nums1 = [2,3,1,4]
print(sumImbalanceNumbers(nums1))  # Output: 3

nums2 = [1,3,3,3,5]
print(sumImbalanceNumbers(nums2))  # Output: 8
← Back to All Questions