data-structures · intermediate · ~30 min

Longest substring without repeating characters

Sliding window + last-seen index map.

Challenge

Find the length of the longest run of distinct characters in a string.

Task

Given a C-string s of ASCII bytes, implement int longest_unique(const char *s) that returns the length of the longest contiguous substring in which every character is distinct.

Input

s: a NUL-terminated ASCII string (bytes 0..127), possibly empty.

Output

int: the length of the longest substring with no repeated characters.

Example

"abcabcbb"   ->   3    ("abc")
"bbbbb"      ->   1    ("b")
"pwwkew"     ->   3    ("wke")
""           ->   0

Edge cases

  • Empty string returns 0.
  • All identical characters return 1; an all-distinct string returns its length.

Rules

  • Solve in O(n) with a sliding window and a last-seen index table (no nested loops).

Why this matters

The sliding-window pattern with a frequency map is one of the highest-yield algorithmic techniques: it appears in network rate-limiters, log analyzers, and DNA sequence search.

Input format

s: NUL-terminated ASCII string (bytes 0..127); may be empty.

Output format

int: length of the longest substring with all distinct characters.

Constraints

O(n) time. No nested loops.

Starter code

int longest_unique(const char *s) { /* TODO */ return 0; }

Common mistakes

Recomputing the start index incorrectly (must use max(start, last_seen+1)); using a hash map when a 128-entry array suffices for ASCII; off-by-one on the length calculation.

Edge cases to handle

Empty string returns 0. All identical characters return 1. All distinct returns strlen.

Complexity

O(n) time, O(128) memory.

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.