data-structures · intermediate · ~30 min

Longest substring without repeating characters

Sliding window + last-seen index map.

Challenge

Given a C-string s of ASCII bytes, return the length of the longest substring with all distinct characters. Implement int longest_unique(const char *s).

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

A null-terminated ASCII string (bytes 0..127).

Output format

The length as int.

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.