Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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] > 1Here, 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.lengthProblem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map
[2,3,1,4]
[1,3,3,3,5]
count-subarrays-with-median-k)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2763: Sum of Imbalance Numbers of All Subarrays
class Solution {
public int sumImbalanceNumbers(int[] nums) {
int n = nums.length;
int ans = 0;
for (int i = 0; i < n; ++i) {
TreeMap<Integer, Integer> tm = new TreeMap<>();
int cnt = 0;
for (int j = i; j < n; ++j) {
Integer k = tm.ceilingKey(nums[j]);
if (k != null && k - nums[j] > 1) {
++cnt;
}
Integer h = tm.floorKey(nums[j]);
if (h != null && nums[j] - h > 1) {
++cnt;
}
if (h != null && k != null && k - h > 1) {
--cnt;
}
tm.merge(nums[j], 1, Integer::sum);
ans += cnt;
}
}
return ans;
}
}
// Accepted solution for LeetCode #2763: Sum of Imbalance Numbers of All Subarrays
package main
// https://space.bilibili.com/206214
func sumImbalanceNumbers(nums []int) (ans int) {
n := len(nums)
for i, x := range nums {
vis := make([]int, n+2)
vis[x] = 1
cnt := 0
for j := i + 1; j < n; j++ {
if x := nums[j]; vis[x] == 0 {
cnt--
cnt += 1 ^ vis[x-1] // 巧妙的是,如果 x 左边没有任何数字,这也算也是对的
cnt += 1 ^ vis[x+1]
vis[x] = 1
}
ans += cnt
}
}
return
}
func min(a, b int) int {
if b < a {
return b
}
return a
}
# Accepted solution for LeetCode #2763: Sum of Imbalance Numbers of All Subarrays
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
// Accepted solution for LeetCode #2763: Sum of Imbalance Numbers of All Subarrays
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #2763: Sum of Imbalance Numbers of All Subarrays
// class Solution {
// public int sumImbalanceNumbers(int[] nums) {
// int n = nums.length;
// int ans = 0;
// for (int i = 0; i < n; ++i) {
// TreeMap<Integer, Integer> tm = new TreeMap<>();
// int cnt = 0;
// for (int j = i; j < n; ++j) {
// Integer k = tm.ceilingKey(nums[j]);
// if (k != null && k - nums[j] > 1) {
// ++cnt;
// }
// Integer h = tm.floorKey(nums[j]);
// if (h != null && nums[j] - h > 1) {
// ++cnt;
// }
// if (h != null && k != null && k - h > 1) {
// --cnt;
// }
// tm.merge(nums[j], 1, Integer::sum);
// ans += cnt;
// }
// }
// return ans;
// }
// }
// Accepted solution for LeetCode #2763: Sum of Imbalance Numbers of All Subarrays
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #2763: Sum of Imbalance Numbers of All Subarrays
// class Solution {
// public int sumImbalanceNumbers(int[] nums) {
// int n = nums.length;
// int ans = 0;
// for (int i = 0; i < n; ++i) {
// TreeMap<Integer, Integer> tm = new TreeMap<>();
// int cnt = 0;
// for (int j = i; j < n; ++j) {
// Integer k = tm.ceilingKey(nums[j]);
// if (k != null && k - nums[j] > 1) {
// ++cnt;
// }
// Integer h = tm.floorKey(nums[j]);
// if (h != null && nums[j] - h > 1) {
// ++cnt;
// }
// if (h != null && k != null && k - h > 1) {
// --cnt;
// }
// tm.merge(nums[j], 1, Integer::sum);
// ans += cnt;
// }
// }
// return ans;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.