Taro Logo

Longest Substring Without Repeating Characters

#3 Most AskedMedium
168 views
Topics:
StringsTwo PointersSliding Windows

Given a string s, find the length of the longest substring without duplicate characters.

Example 1:

Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.

Example 2:

Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.

Constraints:

  • 0 <= s.length <= 5 * 104
  • s consists of English letters, digits, symbols and spaces.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What character set should we expect in the string—is it strictly ASCII, or could it contain Unicode characters like emojis?
  2. How should the algorithm handle an empty string or a string with a length of 1?
  3. Are we guaranteed that the input string will only contain alphanumeric characters, or could it include spaces and special symbols?
  4. If the string consists entirely of identical repeating characters (e.g., "aaaaa"), should the expected return value be 1?
  5. Is the output expected to just be the length of the longest substring, or do we also need to return the actual substring itself?

Brute Force Solution

Approach

The brute force approach to finding the longest sequence of unique characters involves examining every single possible continuous slice of the given text. We methodically check every possible starting point and ending point to see if any repeated characters sneak in, and we keep track of the biggest valid slice we find.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the very first character of the text as a tiny slice.
  2. Check if this slice has any repeating characters, which is easy since it is only one character long.
  3. Expand your slice to include the next character, and check if any letters repeat.
  4. Keep expanding the slice one character at a time until you hit a duplicate letter or reach the end of the text.
  5. Write down the length of this valid slice.
  6. Now, move your starting position to the second character of the text and repeat the entire expansion process.
  7. Do this for every possible starting position in the text, testing every single possible continuous slice.
  8. Compare the lengths of all the valid slices you found during this exhaustive search.
  9. Declare the length of the largest valid slice as your final answer.

Code Implementation

def length_of_longest_substring(input_string):
    max_length = 0

    # Test every possible starting position to examine all continuous slices
    for start_index in range(len(input_string)):
        for end_index in range(start_index, len(input_string)):
            current_slice = input_string[start_index:end_index + 1]

            # Check for duplicates because valid slices must contain only unique characters
            if len(current_slice) == len(set(current_slice)):
                current_length = len(current_slice)

                # Keep track of the biggest valid slice found during exhaustive search
                if current_length > max_length:
                    max_length = current_length

    return max_length

Big(O) Analysis

Time Complexity
O(n²) – To analyze the brute force approach, let n be the length of the input string. The outer loop selects every possible starting position for a slice, resulting in n potential starting points. For each starting point, an inner loop expands the slice character by character until the end of the string or a duplicate is encountered, taking up to n steps. This exhaustive search across all possible starting and ending points leads to approximately n * n/2 total substring evaluations. Simplifying this expression by dropping constants yields a final time complexity of O(n²).
Space Complexity
O(1) – The brute force approach described relies entirely on iterating through starting and ending points without utilizing any auxiliary data structures like hash maps or temporary lists. The algorithm only requires a few primitive integer variables to keep track of indices, current slice boundaries, and the maximum length found so far. Because these scalar variables consume a constant amount of memory that does not scale with the input length N, the auxiliary space remains entirely independent of the size of the text.

Optimal Solution

Approach

Instead of checking every single possible grouping of letters, the most efficient approach uses a growing window that expands and shrinks dynamically. By keeping track of which letters we have already seen, we can quickly skip past duplicates without starting our search all over again.

Here's how the algorithm would work step-by-step:

  1. Imagine sliding a flexible frame across the text, starting from the beginning.
  2. Look at the letters inside your frame one by one, making sure none of them appear more than once.
  3. Keep expanding the front edge of your frame to include the next letter as long as it is completely new.
  4. If you encounter a letter that is already inside your frame, pause your expansion.
  5. Slide the back edge of your frame forward just enough to drop the duplicate letter and any letters before it.
  6. Measure the size of your frame every time it grows, and remember the largest size you achieved.
  7. Continue sliding the front edge forward and adjusting the back edge until you reach the end of the text.
  8. Return the biggest size your frame ever reached, which represents the longest stretch of unique letters.

Code Implementation

def length_of_longest_substring(input_string):
    last_seen_indices = {}
    start_index_of_window = 0
    max_substring_length = 0

    # Iterate through the string, treating the current character as the front edge of our frame.
    for current_index, character in enumerate(input_string):
        if character in last_seen_indices and last_seen_indices[character] >= start_index_of_window:
            # Shrink the window from the back edge to drop the duplicate character and everything before it.
            start_index_of_window = last_seen_indices[character] + 1

        last_seen_indices[character] = current_index

        # Measure the current window size and keep track of the largest size achieved so far.
        current_window_size = current_index - start_index_of_window + 1
        if current_window_size > max_substring_length:
            max_substring_length = current_window_size

    return max_substring_length

Big(O) Analysis

Time Complexity
O(n) – As the front edge of our sliding window iterates through all n characters of the input string one by one, the back edge also moves only forward to skip duplicates. Each character is visited at most twice, once by the front pointer and once by the back pointer. This means the total number of operations scales linearly with the input size. Therefore, the operations approximate a formula of 2n steps, which simplifies to O(n).
Space Complexity
O(min(N, C)) – To keep track of which letters we have already seen inside our sliding frame, we use a hash map or an array that stores the most recent index of each character. As the front edge expands across the text of length N, this data structure grows to store at most N unique characters, or bounded by the size of the character set C (such as 26 for lowercase English letters). Therefore, the auxiliary space complexity scales proportionally to the number of unique elements stored within our tracking structure.

Edge Cases

Empty string input where length is zero
How to Handle:
The sliding window loop safely terminates immediately and returns zero.
String with a single character
How to Handle:
The window size remains one and the function correctly returns one.
String with all identical characters such as aaaaa
How to Handle:
The left pointer jumps past the previous duplicate ensuring the window length never exceeds one.
String with no repeating characters such as abcde
How to Handle:
The right pointer expands to the end of the string and returns the total length.
Characters repeating far apart in a long string
How to Handle:
The hash map stores the latest index of each character allowing the left pointer to jump directly past the old occurrence.
String with special characters spaces or unicode
How to Handle:
Using an integer frequency array or hash map based on character codes naturally accommodates any valid character set.
Maximum length constraints scaling up to large inputs
How to Handle:
The optimized sliding window approach operates in linear time complexity visiting each character at most twice.
0/1037 completed