Longest Streak
A list days holds day numbers when a customer visited a shop, in any order and possibly with repeats. A streak is a run of consecutive day numbers, such as 4, 5, 6.
Write longest_streak(days) that returns the length of the longest streak. For an empty list return 0.
Understand the problem
Be clear about what counts as a streak.
What does longest_streak([100, 4, 200, 1, 3, 2]) return?
The days 1, 2, 3, 4 are all present: a streak of length 4. The list order does not matter. 100 and 200 are lonely streaks of length 1.
What does longest_streak([1, 2, 2, 3]) return? There is a repeated 2.
Days 1, 2, 3 are present, so the streak has length 3. A repeated day is not a new day: do not count it twice.
What does longest_streak([5, 7, 9]) return?
No two days are consecutive, so every day is a streak of length 1.
Try examples by hand
Find a way to know where a streak begins.
In [100, 4, 200, 1, 3, 2], which numbers begin a streak (the number before them is not in the list)?
- 1, 100 and 200
- 1, 2, 3, 4
- Only 1
A number begins a streak when number - 1 is not in the list. 1 has no 0, 100 has no 99 and 200 has no 199. The numbers 2, 3 and 4 each have a predecessor, so they are in the middle of a streak.
If you only try to extend streaks from numbers that begin a streak, how many times is each number visited?
- Many times
- About once
- Never
Each streak is walked from its first number to its last, once. The numbers in the middle are walked as part of one streak and never started from again. That is what makes it fast.
Write the brute force
Do not look for the clever answer yet. Write the simplest version that is correct, even if it is slow. A correct slow answer gives you something to test against and something to improve.
def longest_streak(days):
# Write the simple version here. It only has to be correct, not fast.
pass
Hint 1: a question to ask yourself
If you start at one number, how do you find out how far the streak goes?
Hint 2: the shape of the answer
For every number x in the list, count how long x, x + 1, x + 2, ... stays inside the list (in days), and keep the largest count.
Find the bottleneck
Before you improve anything, find what is slow. Answer these, then write the faster version.
Which two things make the brute force slow?
x in dayssearches a list, and streaks are walked again from their middle- It uses a loop
- It returns a number
Checking x + 1 in days on a list scans the list every time, and starting from every number walks the same streak from each of its members.
Which structure fixes the first problem (checking membership quickly)?
- A list
- A set
- A string
A set checks x in numbers in about one step. Build it once with set(days); it also removes repeated days for free.
Make it faster
Now write the linear version.
def longest_streak(days):
# Write the faster version here.
pass
Hint 1: a question to ask yourself
Which numbers are worth starting a count from?
Hint 2: the pattern
Put the days in a set. Start counting only from days where day - 1 is not in the set, then walk upwards while day + 1, day + 2, ... are in the set.
Hint 3: pseudocode
numbers = set(days)
best = 0
for each day in numbers:
if day - 1 is not in numbers: # the start of a streak
length = 1
while day + length is in numbers: length += 1
best = max(best, length)
return best
Reflect
Brute force: O(n cubed) with a list
def longest_streak(days):
best = 0
for day in days:
length = 1
while day + length in days:
length += 1
best = max(best, length)
return best
Improved: O(n) with a set
def longest_streak(days):
numbers = set(days)
best = 0
for day in numbers:
if day - 1 not in numbers:
length = 1
while day + length in numbers:
length += 1
best = max(best, length)
return best
Another way: sort first, O(n log n)
def longest_streak(days):
if not days:
return 0
values = sorted(set(days))
best = run = 1
for i in range(1, len(values)):
if values[i] == values[i - 1] + 1:
run += 1
else:
run = 1
best = max(best, run)
return best
Pattern: a lookup structure, plus "only start at the beginning". The set makes each membership test one step. The check day - 1 not in numbers makes sure every streak is walked once, from its first number. Without it you get the same answers with far more work.
Two valid ideas: sorting is simpler and fine for most inputs (O(n log n)); the set version is O(n). An interviewer who says "can you do better than sorting?" is asking for the set.
Cost:
| Version | Time | Extra space |
|---|---|---|
List with in |
very slow (about n cubed in the worst case) | O(1) |
| Sort first | O(n log n) | O(n) |
| Set, start only at beginnings | O(n) | O(n) |
What an interviewer might ask next: What if the streak must allow one missing day (a gap of one)? How would the start-of-streak idea change?
import random
VISIBLE = 3
CASES = [
(([100, 4, 200, 1, 3, 2],), 4, 'a streak in the middle of other numbers'),
(([1, 2, 2, 3],), 3, 'a repeated day'),
(([5, 7, 9],), 1, 'no consecutive days'),
(([],), 0, 'no days'),
(([42],), 1, 'one day'),
(([0, -1, -2, 5, 6],), 3, 'negative days'),
(([9, 1, 4, 7, 3, -1, 0, 5, 8, 6],), 7, 'one long streak, unsorted'),
(([1, 3, 5, 7, 2, 4, 6],), 7, 'odd numbers first, then even'),
(([10, 11, 12, 20, 21, 22, 23],), 4, 'two streaks, the second is longer'),
]
def REFERENCE(days):
numbers = set(days)
best = 0
for day in numbers:
if day - 1 not in numbers:
length = 1
while day + length in numbers:
length += 1
best = max(best, length)
return best
LIMIT = 2.0
def PERF():
rng = random.Random(11)
one = list(range(1500))
rng.shuffle(one)
big = list(range(300000))
rng.shuffle(big)
return [('1500 days in one streak', (one,)), ('300000 days in one streak', (big,))]