Longest Substring Without Repeating Characters in Python

In Python, finding the longest substring without repeating characters is a classic string problem. We can solve this using different approaches: the Brute Force method which checks all possible substrings, and the more efficient Sliding Window technique using either a set or dictionary to track character positions.

Common Methods

The main approaches to find the longest substring without repeating characters are:

  • Brute Force: Checks all possible substrings and verifies if they have unique characters.

  • Sliding Window with Set: Uses a set to track characters in the current window and adjusts window boundaries dynamically.

  • Sliding Window with Dictionary: Uses a dictionary to store the last occurrence index of each character for efficient window adjustment.

Method 1: Brute Force Approach

This method checks every possible substring but is inefficient with O(n³) time complexity. It uses nested loops where the outer loop starts from each character, and the inner loop generates all substrings ?

def length_of_longest_substring_brute(s):
    def is_unique(substring):
        return len(set(substring)) == len(substring)
    
    max_length = 0
    longest_substring = ""
    
    for i in range(len(s)):
        for j in range(i + 1, len(s) + 1):
            if is_unique(s[i:j]):
                if j - i > max_length:
                    max_length = j - i
                    longest_substring = s[i:j]
    
    print(f"Longest substring: '{longest_substring}'")
    print(f"Length: {max_length}")
    return max_length

s = "abcabcbb"
length_of_longest_substring_brute(s)
Longest substring: 'abc'
Length: 3

Method 2: Sliding Window with Set

This approach uses two pointers (left and right) to maintain a sliding window. The set tracks characters in the current window, providing O(n) time complexity ?

def length_of_longest_substring_set(s):
    char_set = set()
    left = 0
    max_length = 0
    start_index = 0
    
    for right in range(len(s)):
        # Remove characters from left until no duplicate
        while s[right] in char_set:
            char_set.remove(s[left])
            left += 1
        
        char_set.add(s[right])
        
        # Update maximum length and starting position
        if right - left + 1 > max_length:
            max_length = right - left + 1
            start_index = left
    
    longest_substring = s[start_index:start_index + max_length]
    print(f"Longest substring: '{longest_substring}'")
    print(f"Length: {max_length}")
    return max_length

s = "abcabcbb"
length_of_longest_substring_set(s)
Longest substring: 'abc'
Length: 3

Method 3: Sliding Window with Dictionary

This optimized approach uses a dictionary to store the last occurrence index of each character, allowing the left pointer to jump directly to the optimal position ?

def length_of_longest_substring_dict(s):
    char_index_map = {}
    max_length = 0
    left = 0
    start_index = 0
    
    for right in range(len(s)):
        # If character exists and is within current window
        if s[right] in char_index_map and char_index_map[s[right]] >= left:
            left = char_index_map[s[right]] + 1
        
        char_index_map[s[right]] = right
        
        # Update maximum length and starting position
        if right - left + 1 > max_length:
            max_length = right - left + 1
            start_index = left
    
    longest_substring = s[start_index:start_index + max_length]
    print(f"Longest substring: '{longest_substring}'")
    print(f"Length: {max_length}")
    return max_length

s = "abcabcbb"
length_of_longest_substring_dict(s)
Longest substring: 'abc'
Length: 3

Comparison

Method Time Complexity Space Complexity Best For
Brute Force O(n³) O(n) Small strings, learning
Sliding Window + Set O(n) O(n) General use
Sliding Window + Dict O(n) O(n) Optimal performance

Conclusion

The sliding window with dictionary approach provides the best performance with O(n) time complexity. Use the brute force method only for educational purposes, and prefer sliding window techniques for production code.

Updated on: 2026-03-25T07:38:46+05:30

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements