Find the longest substring without repeating characters.
#include <stddef.h>
size_t longest_unique_substring(const char *s)
{
int last[256];
for (int i = 0; i < 256; i++) last[i] = -1; /* last index each char was seen */
size_t best = 0;
int start = 0; /* left edge of the window */
for (int i = 0; s[i]; i++) {
unsigned char c = (unsigned char)s[i];
if (last[c] >= start) start = last[c] + 1; /* repeat inside window: jump past it */
last[c] = i;
if ((size_t)(i - start + 1) > best) best = (size_t)(i - start + 1);
}
return best;
}
/* "abcabcbb" -> 3 ("abc"), "pwwkew" -> 3 ("wke") */
Points: sliding window: extend the right edge each step, move the left edge past the previous occurrence of a repeated character; each character processed once → O(n), O(1) space with a 256-entry table.