Engineering platform~35 min2s · 256 MBtarget O(n + s) time, O(s) spaceclassic twin: lc-1234minimum-cover · sliding-window-variable · hashing
An engineering platform runs about 60,000 builds a day. Each queued build job is assigned to one of s shards, and each shard runs its own jobs. The queue is balanced when every shard holds the same number of jobs: n / s, its fair share.
After a burst of new jobs, some shards hold too many. To fix this, the scheduler picks one block of consecutive jobs in the queue and sends each job in it to any shard. Jobs outside the block keep their shard. Every moved job repeats its setup, so the team wants the shortest block that balances the queue.
Write shortest_rebalance(shards, s).
shards[i] is the shard of the job at position i of the queue, a number from 1 to s.s is the number of shards. The length n of shards is a multiple of s, so every shard's fair share is n / s.0.Input: shards = [2, 2, 2, 4, 1, 2, 1, 3, 3, 2, 3, 3], s = 4
Output: 5The fair share is 3. Shard 2 holds 5 jobs and shard 3 holds 4. So the block must hold at least 2 jobs of shard 2 and 1 job of shard 3.
The counter missing starts at 3, one for each of those excess jobs. Jobs of shards 1 and 4 never change it.
| right | Joins | missing after joining | Recorded, then the left job leaves | left after | Best |
|---|---|---|---|---|---|
| 0 | 2 | 2 | none | 0 | none |
| 1 | 2 | 1 | none | 0 | none |
| 2 | 2 | 1 | none | 0 | none |
| 3 | 4 | 1 | none | 0 | none |
| 4 | 1 | 1 | none | 0 | none |
| 5 | 2 | 1 | none | 0 | none |
| 6 | 1 | 1 | none | 0 | none |
| 7 | 3 | 0 | positions 0 to 7, 1 to 7, 2 to 7; then 2, 2, 2 leave (missing 0, 0, 1) | 3 | 6 |
| 8 | 3 | 1 | none | 3 | 6 |
| 9 | 2 | 0 | positions 3 to 9, 4 to 9, 5 to 9; then 4, 1, 2 leave (missing 0, 0, 1) | 6 | 5 |
| 10 | 3 | 1 | none | 6 | 5 |
| 11 | 3 | 1 | none | 6 | 5 |
The block at positions 5 to 9 is 2, 1, 3, 3, 2. Its five jobs go 2 to shard 1, 1 to shard 3 and 2 to shard 4, and every shard ends with 3.
Input: shards = [3, 1, 2, 2, 3, 1], s = 3
Output: 0Every shard already holds its fair share of 2 jobs.
Input: shards = [1, 2, 2, 2, 3, 2], s = 3
Output: 2Shard 2 holds 4 jobs, 2 over its share. The block 2, 2 at positions 1 to 2 holds both, and its jobs go to shards 1 and 3.
1 ≤ shards.length ≤ 10^5, and shards.length is a multiple of s1 ≤ s ≤ 1,000 and s ≤ shards.length1 ≤ shards[i] ≤ sGrowing a block from every start until it works is O(n^2). On the large test stress-random, that is about 2.4 × 10^9 steps. Aim for O(n + s).
Checking every shard to see whether a block works costs up to 1,000 steps per check. Keep one missing counter instead, so each step costs O(1).