KatInterview

3. Longest Substring Without Repeating Characters

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the length of the longest substring within a given string s that contains no repeating characters. A substring is a contiguous sequence of characters. For example, in "pwwkew", "wke" is a valid substring with unique characters, but "pwke" is a subsequence, not a substring.

Solution

Longest Substring Without Repeating Characters in Python

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        # Dictionary to store the last seen index of each character.
        char_index_map = {}
        max_length = 0
        left = 0 # The left pointer of the sliding window

        for right, char in enumerate(s):
            # If the character is already in the map and its last seen index is within our current window [left, right],
            # it's a duplicate in the current window.
            if char in char_index_map and char_index_map[char] >= left:
                # Move the left pointer to the position after the last occurrence.
                # This effectively shrinks the window to exclude the duplicate.
                left = char_index_map[char] + 1
            
            # Update the last seen index of the character to the current position.
            char_index_map[char] = right
            
            # Calculate the length of the current valid window and update max_length if it's larger.
            max_length = max(max_length, right - left + 1)
            
        return max_length

Longest Substring Without Repeating Characters in Java

class Solution {
    public int lengthOfLongestSubstring(String s) {
        // Use an array as a direct-access table to store the last seen index of each character.
        // Assuming ASCII character set, size 128 is sufficient. Initialize with -1 to indicate not seen.
        int[] charIndex = new int[128];
        java.util.Arrays.fill(charIndex, -1);
        
        int maxLength = 0;
        int left = 0; // The left pointer of the sliding window

        for (int right = 0; right < s.length(); ++right) {
            char currentChar = s.charAt(right);
            
            // If the character has been seen before AND its last index is within the current window [left, right],
            // it's a duplicate in the current window.
            if (charIndex[currentChar] >= left) {
                // Move the left pointer to the position after the last occurrence of the current character.
                // This effectively shrinks the window to exclude the duplicate.
                left = charIndex[currentChar] + 1;
            }
            
            // Update the last seen index of the current character to the current position.
            charIndex[currentChar] = right;
            
            // Calculate the length of the current valid window and update maxLength if it's larger.
            maxLength = Math.max(maxLength, right - left + 1);
        }
        
        return maxLength;
    }
}

Longest Substring Without Repeating Characters in C++

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        // Use a vector as a direct-access table to store the last seen index of each character.
        // Assuming ASCII character set, size 128 is sufficient. Initialize with -1 to indicate not seen.
        std::vector<int> charIndex(128, -1);
        int maxLength = 0;
        int left = 0; // The left pointer of the sliding window

        for (int right = 0; right < s.length(); ++right) {
            char currentChar = s[right];
            
            // If the character has been seen before AND its last index is within the current window [left, right],
            // it's a duplicate in the current window.
            if (charIndex[currentChar] >= left) {
                // Move the left pointer to the position after the last occurrence of the current character.
                // This effectively shrinks the window to exclude the duplicate.
                left = charIndex[currentChar] + 1;
            }
            
            // Update the last seen index of the current character to the current position.
            charIndex[currentChar] = right;
            
            // Calculate the length of the current valid window and update maxLength if it's larger.
            maxLength = std::max(maxLength, right - left + 1);
        }
        
        return maxLength;
    }
};

Longest Substring Without Repeating Characters in TypeScript

function lengthOfLongestSubstring(s: string): number {
    // Map to store the last seen index of each character.
    const charIndexMap = new Map<string, number>();
    let maxLength = 0;
    let left = 0; // The left pointer of the sliding window

    for (let right = 0; right < s.length; right++) {
        const char = s[right];
        
        // If the character exists in the map and its last seen index is within the current window [left, right],
        // it's a duplicate in the current window.
        if (charIndexMap.has(char) && charIndexMap.get(char)! >= left) {
            // Move the left pointer to the position after the last occurrence.
            // The non-null assertion (!) is safe because we just checked with .has().
            left = charIndexMap.get(char)! + 1;
        }
        
        // Update the last seen index of the character to the current position.
        charIndexMap.set(char, right);
        
        // Calculate the length of the current valid window and update maxLength if it's larger.
        maxLength = Math.max(maxLength, right - left + 1);
    }
    
    return maxLength;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.