Longest Stretch With No Repeat Song
Medium · Sliding Window · about 20 min
A radio station's play log is a list of song ids, songs. Find the longest run of back-to-back plays in which no song repeats.
Return [start, end]: the first and last position of that run (both included). If several runs share the longest length, return the one that starts earliest. For an empty log, return [].
Examples:
longest_fresh_stretch(["a", "b", "c", "a", "b", "c", "b", "b"]) → [0, 2]
longest_fresh_stretch(["d", "v", "d", "f"]) → [1, 3]
Aim for one pass over the log.
Hints
- Keep a map from each song to the last position you saw it.
- If the new song's last position is inside the window (at or after the left edge), move the left edge just past it. Never move the left edge backwards.
- Replace the best answer only when the window is strictly longer, so ties keep the earlier run.
Learn the pattern first: the Sliding Window lesson.
More Sliding Window problems
- Food Stall Moving Average (Easy)
- Badge Scanned Twice Too Soon (Easy)
- Repaint Tiles for the Longest Run (Medium)
- Scrambled Code Hidden in a Log (Medium)
- Fewest Orders to Hit the Goal (Medium)
- Shortest Note That Covers Every Letter (Hard)
- Rolling Peak of a Sensor (Hard)