Longest Streak

Longest Streak

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.

Examples

5 → 5 → 7 → 7 → 7 → 6   // → 3   (the run of 7s)
9 → 9                    // → 2
1 → 2 → 3                // → 1

Walkthrough

Thinking it through

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.

Why you need two counters, not one

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.

Building the approach

  1. Keep three things as you traverse: the current run's length, the previous node's value, and the best run length found so far.
  2. At each node, ask: does this value match the previous node's? If yes, extend the current run by one. If no (or if this is the first node), reset the current run to length one.
  3. Compare the current run against the best-so-far, and update it if the current run just became the longest.
  4. Remember this node's value as "previous," then advance.

Why comparing to the immediately preceding node is enough

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.

The empty list and single-node cases

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.

Why this is efficient

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.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.