Maps app~25 min2s · 256 MBtarget O(26 × n) time, O(n) spaceclassic twin: lc-387hashing
A navigation app records the road sign seen at every step of a route, one letter for each sign type. The app shows a hint about the first sign that stands alone in a stretch of road.
For every stretch of w consecutive steps, a sign that appears exactly once in that stretch is a stand-alone sign. Your team lead asks: "For each stretch, where is the first stand-alone sign?"
Write first_unique_in_windows(signs, w).
signs is the route, one letter for each step. The first step has position 0.w is the length of a stretch. A stretch is w consecutive steps, and the route has len(signs) - w + 1 stretches, from left to right.-1 if no letter does.Input: signs = "abcbad", w = 4
Output: [0, 2, 2]The route has 3 stretches of 4 steps. For each stretch, count its letters and pick the leftmost letter with count 1.
| Window start | Window | Counts | Seen once | Answer |
|---|---|---|---|---|
| 0 | abcb | a:1, b:2, c:1 | a at 0, c at 2 | 0 |
| 1 | bcba | a:1, b:2, c:1 | a at 4, c at 2 | 2 |
| 2 | cbad | a:1, b:1, c:1, d:1 | a at 4, b at 3, c at 2, d at 5 | 2 |
Input: signs = "acc", w = 2
Output: [0, -1]A stretch of cc has no stand-alone sign, so the answer is -1.
Input: signs = "dcba", w = 1
Output: [0, 1, 2, 3]With a stretch of 1 step, every sign is alone, so each position answers itself.
1 ≤ len(signs) ≤ 100,0001 ≤ w ≤ len(signs)signs uses only the letters a to z.Checking each stretch from scratch is far too slow when a stretch has 50,000 steps. Only 26 letters exist, so a table of 26 counts, updated as the stretch moves by one step, answers each stretch in about 26 steps. That is 2,600,000 steps in all.