data-structures · intermediate · ~30 min
Sliding window + last-seen index map.
Find the length of the longest run of distinct characters in a string.
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.
s: a NUL-terminated ASCII string (bytes 0..127), possibly empty.
int: the length of the longest substring with no repeated characters.
"abcabcbb" -> 3 ("abc")
"bbbbb" -> 1 ("b")
"pwwkew" -> 3 ("wke")
"" -> 0
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.
s: NUL-terminated ASCII string (bytes 0..127); may be empty.
int: length of the longest substring with all distinct characters.
O(n) time. No nested loops.
int longest_unique(const char *s) { /* TODO */ return 0; }
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.
Empty string returns 0. All identical characters return 1. All distinct returns strlen.
O(n) time, O(128) memory.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.