This visualization was AI-generated and may contain errors. View original problem on LeetCode

Longest Substring Without Repeating Characters

Find the length of the longest substring without repeating characters using the sliding window technique with a hash set to track unique characters.

Sliding Window Hash Set LC 3 Medium

Problem Statement

Given a string s, find the length of the longest substring without repeating 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.

Interactive Visualization

1000ms
Current Window Length
0
Max Length Found
0
Best Substring Found
Hash Set (Current Window Characters)
Empty
Code
fun lengthOfLongestSubstring(s: String): Int {    val charSet = mutableSetOf<Char>()    var left = 0    var maxLen = 0        for (right in s.indices) {        while (s[right] in charSet) {            charSet.remove(s[left])            left++        }        charSet.add(s[right])        maxLen = maxOf(maxLen, right - left + 1)    }    return maxLen}
Ready to start

How It Works

Key Insight

The sliding window technique maintains a variable-size window of unique characters. We use a hash set to efficiently check for duplicates in O(1) time. When we encounter a duplicate character, we shrink the window from the left until the duplicate is removed.

Algorithm Steps

  1. Initialize: Create an empty hash set, set left = 0, and max_len = 0
  2. Expand Window: For each position right from 0 to len(s) - 1
  3. Remove Duplicates: While s[right] is in the set, remove s[left] and increment left
  4. Add Character: Add s[right] to the set
  5. Update Maximum: Update max_len with the current window size (right - left + 1)
  6. Return: After processing all characters, return max_len

Complexity Analysis

Time Complexity: O(n) Each character is visited at most twice (once by right, once by left)
Space Complexity: O(min(n, m)) where n is string length and m is the character set size (at most 128 ASCII or 256 extended ASCII)