01

1. Restate the problem in your own words

Before writing code, say what goes in, what comes out, and what the edge cases return. If you cannot, you have not finished reading.

For Longest Substring Without Repeating Characters: the input is a string, and the output is a number, the length of the longest run of neighbouring characters with no character used twice.

  • A substring is one unbroken piece. For 'pwwkew' the answer is 3 ('wke'). 'pwke' skips a character, so it does not count.
  • The empty string returns 0.
  • Characters can be letters, digits, symbols and spaces, so an array of 26 counters is not enough.
02

2. Write the simplest version that is correct

Start with the slow, obvious solution. It gives you something correct to test the fast version against, and writing it shows where the wasted work is.

Here: try every start position, and extend to the right until a character repeats.

Python: brute force, O(n²)
def longest_brute(s):
    best = 0
    for i in range(len(s)):
        seen = set()
        for j in range(i, len(s)):
            if s[j] in seen:
                break
            seen.add(s[j])
            best = max(best, j - i + 1)
    return best

The waste is now visible. When the scan from start i stops at a repeat, the next scan from i + 1 checks almost the same characters again. A faster version should keep what it already knows.

03

3. State the rule the loop must keep true

A rule that holds before and after every loop step is called an invariant. Writing it down tells you exactly what each line of the loop is for.

For this problem: the window from left to right never contains the same character twice. Each step adds one character on the right. If that breaks the rule, move left forward until the rule holds again. The answer is the largest window seen.

04

4. Write it with names that say what they hold

Names carry the reasoning. left, right and last_seen let you read the loop against the rule from step 3. i, j and d do not.

Python: sliding window, O(n)
def length_of_longest_substring(s):
    last_seen = {}      # character -> index where it last appeared
    left = 0
    best = 0
    for right, ch in enumerate(s):
        if ch in last_seen and last_seen[ch] >= left:
            left = last_seen[ch] + 1
        last_seen[ch] = right
        best = max(best, right - left + 1)
    return best

When ch was last seen inside the window, left jumps to one past that position, which removes the earlier copy in one move. Each character is handled once, so the time is O(n).

05

5. Test the edges before the normal case

The examples in the problem statement usually pass. The bugs are in the inputs nobody shows you. Pick tests that each attack one part of the code.

The test that matters most here is 'abba'. Suppose the check last_seen[ch] >= left is left out, which is a common first draft. Follow it:

Python: the edge tests
assert length_of_longest_substring("") == 0
assert length_of_longest_substring("bbbbb") == 1
assert length_of_longest_substring("abba") == 2
assert length_of_longest_substring("pwwkew") == 3
assert length_of_longest_substring("a b") == 3

The old position of 'a' was outside the window, so it should have been ignored. That is what >= left does. Without the 'abba' test, this bug passes every example in the problem statement.

  • right = 0, 'a': window 'a', best 1.
  • right = 1, 'b': window 'ab', best 2.
  • right = 2, 'b': last seen at 1, so left = 2. Window 'b'.
  • right = 3, 'a': last seen at 0, so left = 1. left moved backwards. The window is now 'bba', length 3, and the function returns 3. The correct answer is 2.
06

Check the fast version against the slow one

You kept the brute force from step 2 for this. Run both on many small random strings and stop at the first difference. Small alphabets and short strings produce repeats quickly, so bugs like the one above show up within a few hundred tries.

Python: random comparison
import random

for _ in range(2000):
    s = "".join(random.choice("ab ") for _ in range(random.randint(0, 8)))
    assert length_of_longest_substring(s) == longest_brute(s), s
07

The loop in one list

The same five steps work on any problem. They take a few minutes and save most of the time people lose to wrong submissions.

  • Restate: input, output, edge cases.
  • Brute force: correct first, and look for the repeated work.
  • Invariant: one sentence the loop keeps true.
  • Code: names that match the invariant.
  • Test: empty, one element, all equal, and the case that makes a pointer move the wrong way.