solulubeta
Sign in
Story Problems / Strings
02.01 · Problem

Longest Run of Distinct Badges

Medium Sliding window + last-seen index Free

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
  1. Keep last[c] = last index of character c and a window start left.
  2. When c was seen inside the window (last[c] ≥ left), jump left to last[c] + 1.
  3. 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.

Loading the workspace…
Mark this problem as solved when you are finished.

Item 21 of 94 · updated 2026-10-12