Longest Run of Distinct Badges
At a stadium gate, each guest’s badge is scanned and a letter code is recorded. The security head wants the longest run of consecutive scans where every letter is different. Given the scan string, return the length of that longest run.
Examples
Example 1
Input: scans = "abcabcbb"
Output: 3
The run abc at the start already holds three different letters, and the next scan repeats the a, so the run has to restart. Every later run hits a repeat by its fourth letter too, so the longest run is 3.
Example 2
Input: scans = "bbbbb"
Output: 1
Constraints
scans holds one letter per guest, in the order they were scanned.
The run must be a stretch of consecutive scans, and no letter inside it may repeat. Return the length of the longest such run.
How to solve it
Hint
“Longest substring without repeating characters” — a window that must stay duplicate-free.
Approach: Sliding window + last-seen index
- Keep
last[c]= last index of character c and a window startleft. - When c was seen inside the window (last[c] ≥ left), jump
leftto last[c] + 1. - Update
last[c]and the best length.
Check with the example. “abc” is the longest run with no repeated letter.
Complexity: O(n) time, O(alphabet) space.
The reference solutions in all four languages are in the Solutions tab of the workspace below.
Item 21 of 94 · updated 2026-10-12