The "imbalance number" of an array is the number of integers x such that x and x + 1 both exist in the array, but they are not "adjacent" in terms of sorted value (meaning x+1 is present but x's contribution to a contiguous sorted range is missing something). More specifically, in a sorted version of the array, it's the count of gaps larger than 1 between consecutive elements. The task is to find the sum of imbalance numbers of all possible subarrays of a given array.
This Hard-level Google question evaluates a candidate's ability to optimize a problem involving every possible subarray (O(N²)). It tests whether they can update a complex property (imbalance) incrementally as they expand a subarray, rather than re-calculating it from scratch. It also tests knowledge of data structures like Hash Sets or sorted containers for tracking neighbors.
The pattern is "Incremental Subarray Enumeration with Hash Set."
i.i, expand the subarray to the right one element at a time (j = i to n-1).[i...j].nums[j], update the imbalance count. Adding a number might "fill a gap" between existing numbers (decreasing imbalance) or "create a new number" that doesn't have neighbors (increasing imbalance).
By doing this, the total complexity is O(N²), which is acceptable for the typical constraints of this problem.Subarray: [1, 3]. Sorted: [1, 3]. Gap between 1 and 3 is > 1. Imbalance = 1.
If we add 2 to get [1, 3, 2]:
[1, 2, 3].val-1 and val+1 are already in the set when val is added.x have x+1 in the set).Practice "Incremental DP" or "Incremental property tracking" for subarrays. If you can update the answer for [i...j] to get the answer for [i...j+1] in O(1) or O(log N), you can solve most subarray problems efficiently.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Find the Maximum Number of Elements in Subset | Medium | Solve | |
| Maximum Square Area by Removing Fences From a Field | Medium | Solve | |
| Number of Black Blocks | Medium | Solve | |
| Count Special Quadruplets | Easy | Solve | |
| Form Smallest Number From Two Digit Arrays | Easy | Solve |