Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources
Longest Substring Without Repeating Characters

Longest Substring Without Repeating Characters

Problem Statement

Given a string, find the length of the longest substring without repeating characters. This is a medium-level problem that involves sliding window techniques and character tracking to identify the longest unique substring efficiently.

Example

Input: s = "abcabcbb"

Output: 3 ("abc" is the longest substring without repeats)

Input: s = "bbbbb"

Output: 1 ("b" is the longest)

Input: s = "pwwkew"

Output: 3 ("wke" is the longest)

Code

Java
Python
JavaScript
public class Solution {
    public int lengthOfLongestSubstring(String s) {
        Map charMap = new HashMap<>();
        int maxLength = 0, start = 0;
        
        for (int end = 0; end < s.length(); end++) {
            char current = s.charAt(end);
            if (charMap.containsKey(current)) {
                start = Math.max(start, charMap.get(current) + 1);
            }
            charMap.put(current, end);
            maxLength = Math.max(maxLength, end - start + 1);
        }
        return maxLength;
    }
}
            
def length_of_longest_substring(s):
    char_map = {}
    max_length = 0
    start = 0
    
    for end, char in enumerate(s):
        if char in char_map and char_map[char] >= start:
            start = char_map[char] + 1
        char_map[char] = end
        max_length = max(max_length, end - start + 1)
    return max_length

# Example usage
print(length_of_longest_substring("abcabcbb"))  # 3
print(length_of_longest_substring("bbbbb"))     # 1
print(length_of_longest_substring("pwwkew"))    # 3
            
function lengthOfLongestSubstring(s) {
    let charMap = new Map();
    let maxLength = 0, start = 0;
    
    for (let end = 0; end < s.length; end++) {
        let current = s[end];
        if (charMap.has(current) && charMap.get(current) >= start) {
            start = charMap.get(current) + 1;
        }
        charMap.set(current, end);
        maxLength = Math.max(maxLength, end - start + 1);
    }
    return maxLength;
}

// Example usage
console.log(lengthOfLongestSubstring("abcabcbb")); // 3
console.log(lengthOfLongestSubstring("bbbbb"));    // 1
console.log(lengthOfLongestSubstring("pwwkew"));   // 3
            

Explanation

  • Use a sliding window with start and end pointers.
  • Track character positions in a map to detect repeats.
  • If a repeat is found within the current window, move the start pointer past the last occurrence.
  • Update the map with the current character’s position and compute the window length.
  • Keep track of the maximum length seen so far.

Note

Time complexity is O(n) where n is the string length. Space complexity is O(min(m, n)) where m is the size of the character set.