#3

Longest Substring Without Repeating Characters

Medium
Hash TableStringSliding WindowHash MapArrayTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution (Hash Map)
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a sliding window approach with a hash map to track the last seen index of each character. This allows us to efficiently expand and contract the window to find the longest substring without duplicates.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a hash map to store the last index of each character and two pointers for the sliding window.
  2. 2Step 2: Iterate through the string with one pointer, expanding the window.
  3. 3Step 3: If a character is found that is already in the hash map and is within the current window, move the left pointer to the right of the last seen index of that character.
  4. 4Step 4: Update the maximum length of the substring found.
solution.py15 lines
1# Full working Python code with comments
2
3def longest_substring_hash_map(s):
4    char_index = {}
5    max_length = 0
6    left = 0
7    for right in range(len(s)):
8        if s[right] in char_index:
9            left = max(left, char_index[s[right]] + 1)
10        char_index[s[right]] = right
11        max_length = max(max_length, right - left + 1)
12    return max_length
13
14# Example usage
15print(longest_substring_hash_map('abcabcbb'))  # Output: 3

Complexity note: The time complexity is O(n) because we traverse the string once. The space complexity is O(n) due to the hash map storing the last index of each character.

  • 1The sliding window technique is essential for optimizing problems involving substrings, as it allows for efficient expansion and contraction of the search space.
  • 2Using a hash map to track character indices helps avoid unnecessary checks and allows for quick updates to the substring boundaries.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.