ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Longest Substring Without Repeating Characters (Sliding Window)

Python

Goal -- WPM

Ready
Exercise Algorithm Area
1def lengthOfLongestSubstring(s):
2"""Finds the length of the longest substring without repeating characters."""
3char_map = {}
4max_length = 0
5start = 0
6
7for end in range(len(s)):
8# If the character is already in the map and its index is within the current window
9if s[end] in char_map and char_map[s[end]] >= start:
10# Move the start of the window to the right of the last occurrence of the character
11start = char_map[s[end]] + 1
12
13# Update the last seen index of the character
14char_map[s[end]] = end
15
16# Calculate the current window length and update max_length if it's greater
17current_length = end - start + 1
18max_length = max(max_length, current_length)
19
20return max_length
Algorithm description viewbox

Longest Substring Without Repeating Characters (Sliding Window)

Algorithm description:

This problem involves finding the longest substring within a given string that does not contain any repeating characters. It's a classic sliding window problem. This technique is widely applicable in string manipulation tasks, such as text editors, search algorithms, and data validation.

Algorithm explanation:

The sliding window approach uses two pointers, `start` and `end`, to define a window within the string. A hash map (dictionary) `char_map` stores the last seen index of each character. As the `end` pointer moves forward, if a character is encountered that is already within the current window (its last seen index is greater than or equal to `start`), the `start` pointer is moved to the right of that character's previous occurrence to ensure uniqueness. The `max_length` is updated at each step. Time complexity is O(n) because each character is visited at most twice (by `start` and `end` pointers). Space complexity is O(min(n, alphabet_size)) for the hash map.

Pseudocode:

function lengthOfLongestSubstring(s):
  char_map = empty map
  max_length = 0
  start = 0

  for end from 0 to length(s) - 1:
    current_char = s[end]
    if current_char is in char_map and char_map[current_char] >= start:
      start = char_map[current_char] + 1

    char_map[current_char] = end
    current_length = end - start + 1
    max_length = max(max_length, current_length)

  return max_length