[Python][Coding Pattern] Longest Unique Substring

Longest Unique Substring

Purpose

We need to find the longest substring from the input string that contains no repeated characters.

- The input may be empty.

- If multiple substrings of the same length are found, return the first one.

- The logic is built on the sliding window technique.

Key Idea

We slide a window using two pointers:

- left marks the start of the current unique window

- right moves character by character through the string

To track uniqueness, we use a set.

We also remember the maximum length and start index of the longest valid substring seen so far.

Step-by-step

1. Initialize a set

A `seen` set keeps track of characters in the current window so we can detect duplicates quickly.


2. Declare tracking variables

- left = 0: the left boundary of the current window

- max_len = 0: the length of the best substring found so far

- start_index = 0: the index where that best substring starts


3. Start a loop with `right` over the string

The loop runs through each character’s index from 0 to the end.


4. Check for duplicates using the `seen` set

If s[right] is already in seen, we shrink the window from the left.

That’s because we’ve just hit a repeat, which breaks the unique requirement.

5. Use a `while` loop to remove characters from `seen`

Keep removing characters from the left of the window using set.remove(s[left]) until the repeated character is gone.

This ensures that the current window always contains unique characters only.

6. Move the left index forward

Every time we remove a character from the left, increment left += 1 to shift the window.

7. Add the current character to `seen`

After ensuring uniqueness, add s[right] to the set.

8. Check if this window is longer than the previous best

Use the formula right - left + 1 to get the current window’s length.

If this is strictly greater than max_len, update max_len and set start_index = left.

9. Continue looping through the entire string

This ensures we check all possible substrings.

10. Return the result using slicing

At the end, return the longest unique substring using slicing:

s[start_index:start_index + max_len]

def longest_unique_substring(s: str) -> str:
    # Return the longest substring of s that contains no repeating characters.
    # In case of ties, return the first one encountered.
    # Input may be empty.
    # The input string will only contain ASCII characters.

    seen = set()
    left = 0
    max_len = 0
    start_index = 0

    for right in range(len(s)):
        while s[right] in seen:
            seen.remove(s[left])
            left += 1
        seen.add(s[right])
        if right - left + 1 > max_len:
            max_len = right - left + 1
            start_index = left
   
    return s[start_index:start_index + max_len]


if __name__ == '__main__':
    assert longest_unique_substring("abcabcbb") == "abc", 'test 1 failed'
    assert longest_unique_substring("bbbbb") == "b", 'test 2 failed'
    assert longest_unique_substring("pwwkew") == "wke", 'test 3 failed'
    assert longest_unique_substring("abcdef") == "abcdef", 'test 4 failed'
    assert longest_unique_substring("") == "", 'test 5 failed'

Comments