Online store~35 min2s · 256 MBtarget O(n) time, O(m) spaceminimum-cover · sliding-window-variable · hashing
The home page of an online store shows a carousel of banners that never stops. After the last banner, the first one comes back, so the banners form a loop.
Each banner belongs to a product category, stored as a category id. A visitor sees a stretch of consecutive banners on the loop, and the stretch may pass the last banner and carry on from the first.
Your team lead says: "Find the shortest stretch of the loop that shows every category at least once. We will use it as the default screen on small phones."
Write shortest_loop_stretch(categories).
categories[i] is the category id of banner i, in loop order. Banner n - 1 is followed by banner 0.n - 2, n - 1 and 0.categories.n.Input: categories = [30, 10, 10, 10, 20, 20, 10]
Output: 3A first pass finds three categories, so missing starts at 3, and best starts at 7, the whole loop. The code reads the list twice over, so index right means banner right mod 7. The table shows the counts after the join, and the lengths recorded while the stretch includes every category.
| right | Banner | Joins | missing after the join | Recorded lengths, then banners leave | left after | best |
|---|---|---|---|---|---|---|
| 0 | 0 | 30 | 2 | none | 0 | 7 |
| 1 | 1 | 10 | 1 | none | 0 | 7 |
| 2 | 2 | 10 | 1 | none | 0 | 7 |
| 3 | 3 | 10 | 1 | none | 0 | 7 |
| 4 | 4 | 20 | 0 | 5; banner 0 (30) leaves, missing 1 | 1 | 5 |
| 5 | 5 | 20 | 1 | none | 1 | 5 |
| 6 | 6 | 10 | 1 | none | 1 | 5 |
| 7 | 0 | 30 | 0 | 7, 6, 5, 4, 3; banners 1, 2, 3, 4 leave with missing 0, then banner 5 (20) leaves, missing 1 | 6 | 3 |
| 8 to 10 | 1 to 3 | 10 | 1 | none | 6 | 3 |
| 11 | 4 | 20 | 0 | 6, 5; banner 6 (10) leaves, missing 0, then banner 0 (30) leaves, missing 1 | 8 | 3 |
| 12 | 5 | 20 | 1 | none | 8 | 3 |
At right = 7 the banner wraps to the start. Banners 5, 6 and 0, with categories 20, 10 and 30, are the shortest stretch.
Input: categories = [5, 5, 5]
Output: 1There is one category, so any single banner shows it.
Input: categories = [40, 10, 20, 30]
Output: 4Every banner is a different category, so the shortest stretch is the whole loop.
1 ≤ categories.length ≤ 10^51 ≤ categories[i] ≤ 10^6Starting at every banner and walking round the loop until every category has shown is O(n^2) when one category is rare. On the large test stress-rare, a category shows once, at banner 50,000, so the first attempt takes about 5 × 10^9 steps. Aim for O(n).
Category ids go up to 10^6, so count them in a hash map. The categories are not given as a list: a first pass finds how many there are.