Return the length of the longest run of consecutive nodes with the same value.
An empty list has a longest streak of 0.
longestStreak(head)
Input format: space-separated node values.
5 → 5 → 7 → 7 → 7 → 6 // → 3 (the run of 7s)
9 → 9 // → 2
1 → 2 → 3 // → 1
Finding the longest run of equal consecutive values means tracking two related but distinct things as you walk: how long the run currently in progress is, and the longest run seen so far. Conflating these into one variable is a common mistake — the current run can end and get replaced by a shorter one, but the best-so-far must never shrink.
If you only tracked the current run and returned it at the end, you'd get whatever run happens to be active at the last node — wrong whenever the longest run is in the middle and a shorter one trails off at the end. You need a second value, the best-so-far, that only ever increases.
A "streak" is consecutive equal values, so the only thing that matters is whether this node continues the immediately preceding value's run — not whether it matches something further back. You never need to remember more than one previous value.
An empty list never enters the loop, so the best-so-far stays at zero — the correct "no streak" answer. A single-node list runs the loop once, starts a run of length one, and that becomes both the current and best run — correctly a streak of one.
Each node is visited once with constant work per step, so total work is linear — and since you must inspect every node to be sure you haven't missed a longer run, this is as good as it gets.
def longest_streak(head):
best = 0
curr = 0
prev = 0
node = head
while node is not None:
if curr > 0 and node.val == prev:
curr += 1
else:
curr = 1
prev = node.val
if curr > best:
best = curr
node = node.next
return best
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.