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.

  • floors has 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