Opening the reading…
Opening the reading…
HASHING › IMPLEMENTARY PROBLEMS
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →For a fixed subarray, sort its values and count the adjacent gaps larger than 1. When you append one new value x, only the position around x can change; every gap between values smaller than x or larger than x remains exactly as it was. This means you do not need to sort each subarray again.
If x already occurs, inserting another copy creates a gap of zero and does not change any gap larger than 1. If x is new, look only for x - 1 and x + 1 among the values already present. With neither neighbor, x creates one new separated region. With one neighbor, it joins that region. With both neighbors, it connects two previously separate regions, so the imbalance decreases by 1.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(n^2) | For each of the n left endpoints, the right endpoint advances through the remaining elements once. Membership checks, marking, and the imbalance update each take constant time, so the work is the sum of 1 through n rather than repeated sorting. |
| Space | O(n) extra | The membership array uses n + 2 markers and is rebuilt for each left endpoint. The returned integer is a scalar, so there is no output array to exclude; the bound remains O(n) even for the longest possible input. |
#include <vector>
using namespace std;
class Solution {
public:
int sumImbalanceNumbers(vector<int>& nums) {
int n = nums.size();
int total = 0;
for (int i = 0; i < n; ++i) {
vector<int> seen(n + 2, 0);
int imbalance = 0;
for (int j = i; j < n; ++j) {
int x = nums[j];
if (!seen[x]) {
seen[x] = 1;
int neighbors = (seen[x - 1] ? 1 : 0)
+ (seen[x + 1] ? 1 : 0);
imbalance += 1 - neighbors;
}
total += imbalance;
}
}
return total;
}
};The expression imbalance += 1 - neighbors is the central line. Marking x before checking its neighbors is safe because the checks ask only about x - 1 and x + 1. The seen array has two spare positions, so x - 1 is valid when x is 1 and x + 1 is valid when x is n; both boundary checks simply find an absent marker.