intermediate · sliding window · hashing · strings

The longest stretch without a repeated letter

Problem

Given a lowercase word, find the length of the longest contiguous stretch in which no letter repeats.

Constraints

  • 0 ≤ length ≤ 32 (visualization limit)
  • letters a–z only

Examples

"abcabcbb" → 3 — "abc".

"pwwkew" → 3 — "wke"; "pwke" is not contiguous.

Show the solution

Variable sliding window with last-seen positions

The window [left, right] never contains a repeat. A repeat of s[right] inside the window forces left past its previous position; nothing else needs to move.

Why it is correct

Invariant: s[left..right] has no repeated letter. After each step it is the longest such window ending at right (left only moves as far as needed). The answer is the maximum over all right.

Complexity

Time O(n) expected, extra space O(min(n, alphabet)). right moves n times; left only moves forward; every step does O(1) expected map work.

For contrast: Check every substring for repeats. That costs O(n³), or O(n²) with a set per start time and O(alphabet) space.

Edge cases

  • Empty string: 0.
  • All letters equal: 1.
  • A stale last-seen position before left must be ignored (the "seen ≥ left" check).

Common mistakes

  • Moving left backwards to a stale position (missing the seen ≥ left check).
  • Shrinking one step at a time with a set: still O(n) but more work; jumping is simpler.

Step through it

The solution in four languages

Each is checked against one shared set of cases and a randomized comparison with a brute-force reference.

namespace Bekadan.Dsa.Examples.Problems;
 
public static class LongestUniqueSubstring
{
    /// <summary>Length of the longest substring without a repeated character. Expected O(n) time.</summary>
    public static int Length(string word)
    {
        var last = new Dictionary<char, int>();
        int left = 0, best = 0;
        for (int right = 0; right < word.Length; right++)
        {
            if (last.TryGetValue(word[right], out int seen) && seen >= left)
                left = seen + 1; // jump past the earlier copy
            last[word[right]] = right;
            best = Math.Max(best, right - left + 1);
        }
        return best;
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Problems/LongestUniqueSubstring.cs

def length(word: str) -> int:
    """Length of the longest substring without a repeated character. Expected O(n) time."""
    last: dict[str, int] = {}
    left = best = 0
    for right, char in enumerate(word):
        if char in last and last[char] >= left:
            left = last[char] + 1  # jump past the earlier copy
        last[char] = right
        best = max(best, right - left + 1)
    return best

Tested on CPython 3.14.0 · examples/python/dsa_examples/problems/longest_unique_substring.py

package dev.bekadan.dsa.problems;
 
import java.util.HashMap;
import java.util.Map;
 
public final class LongestUniqueSubstring {
    private LongestUniqueSubstring() {
    }
 
    /** Length of the longest substring without a repeated character. Expected O(n) time. */
    public static int length(String word) {
        Map<Character, Integer> last = new HashMap<>();
        int left = 0, best = 0;
        for (int right = 0; right < word.length(); right++) {
            char c = word.charAt(right);
            Integer seen = last.get(c);
            if (seen != null && seen >= left) {
                left = seen + 1; // jump past the earlier copy
            }
            last.put(c, right);
            best = Math.max(best, right - left + 1);
        }
        return best;
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/problems/LongestUniqueSubstring.java

#pragma once
 
#include <algorithm>
#include <cstddef>
#include <string_view>
#include <unordered_map>
 
namespace bekadan::dsa::problems {
 
// Length of the longest substring without a repeated character. Expected O(n) time.
inline std::size_t longest_unique_substring(std::string_view word) {
    std::unordered_map<char, std::size_t> last;
    std::size_t left = 0, best = 0;
    for (std::size_t right = 0; right < word.size(); ++right) {
        if (auto it = last.find(word[right]); it != last.end() && it->second >= left)
            left = it->second + 1;  // jump past the earlier copy
        last[word[right]] = right;
        best = std::max(best, right - left + 1);
    }
    return best;
}
 
}  // namespace bekadan::dsa::problems

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/problems/longest_unique_substring.hpp