Longest Streak of Floors
Medium · Arrays & Hashing · about 20 min
A test elevator logged every floor it stopped at, in no particular order. Floors are whole numbers (basements are negative) and a floor can appear many times.
Return the length of the longest streak of consecutive floor numbers that all appear in the log, like 3, 4, 5, 6. Return 0 for an empty log.
floorshas 0 to 100,000 numbers.- Aim for O(n) time.
Example:
longest_floor_streak([5, -1, 3, 0, 4, 6, 1]) → 4 (floors 3, 4, 5, 6; the other streak -1, 0, 1 has length 3)
Hints
- A set lets you ask whether a floor was visited in O(1).
- Which floors can be the first floor of a streak?
- Only start counting at x when x - 1 is not in the set.
Learn the pattern first: the Arrays & Hashing lesson.
More Arrays & Hashing problems
- First Badge Scanned Twice (Easy)
- Spell It With Tiles (Easy)
- Two Parcels, Exact Load (Easy)
- First One-of-a-Kind Character (Easy)
- Group Words With the Same Letters (Medium)
- Trending Hashtags (Medium)
- Everyone Else's Product (Medium)
- First Free Ticket Number (Hard)
- Most Lamp Posts in One Line (Hard)