Hero Image

Whether you are preparing for a software engineering technical interview at FAANG or just brushing up on your algorithm skills, the "Longest Substring Without Repeating Characters" is a must-know problem. It frequently appears in coding interviews and is the perfect candidate to teach you the powerful Sliding Window technique.

In this comprehensive guide, we will break down the problem, explain the sliding window approach, and provide an optimal solution in Python. We'll also cover the time and space complexity so you can confidently discuss your solution with any interviewer.


Understanding the Problem

The Challenge: Given a string s, find the length of the longest substring without repeating characters.

For example:

  • Input: s = "abcabcbb"

  • Output: 3

  • Explanation: The answer is "abc", with the length of 3.

  • Input: s = "bbbbb"

  • Output: 1

  • Explanation: The answer is "b", with the length of 1.

  • Input: s = "pwwkew"

  • Output: 3

  • Explanation: The answer is "wke", with the length of 3. Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.

The Inefficient Approach (Brute Force)

A naive approach would be to check every possible substring, verify if it has any duplicate characters, and keep track of the maximum length found. However, this brute-force method generates O(n^2) substrings, and checking each one takes O(n) time, resulting in an unacceptable O(n^3) time complexity.

We can do much better!

Enter the Sliding Window Technique

The sliding window technique is ideal for finding subarrays or substrings that satisfy certain conditions. Instead of repeatedly checking overlapping segments from scratch, we "slide" a window (defined by a left and a right pointer) over the data structure.

Sliding Window Diagram

Here is how we can apply the sliding window approach to our longest substring problem:

  1. Initialize Pointers: Create two pointers, left and right, both starting at the beginning of the string (index 0).
  2. Use a Data Structure specifically a Set: We will use a Set (or a Dictionary/Hash Map) to keep track of the characters currently within our window to check for duplicates in O(1) time.
  3. Expand the Window: Move the right pointer one step at a time.
    • If the character at right is not in our set, we add it, calculate the current window length (right - left + 1), and update our maximum length.
    • If the character at right is in our set, we have found a repeating character. We must now "shrink" the window from the left. We remove the character at the left pointer from the set and increment left. We continue shrinking until the duplicate character is removed from the window.
  4. Repeat: Continue expanding and shrinking until the right pointer reaches the end of the string.

Python Solution: Optimal Sliding Window

Let's translate this logic into clean, efficient Python code:

def lengthOfLongestSubstring(s: str) -> int:
    char_set = set()
    left = 0
    max_length = 0

    for right in range(len(s)):
        # If we see a duplicate, shrink the window from the left
        while s[right] in char_set:
            char_set.remove(s[left])
            left += 1
            
        # Add the current character to the window
        char_set.add(s[right])
        
        # Update the maximum length found so far
        max_length = max(max_length, right - left + 1)

    return max_length

Python Developer Solving Algorithm

Complexity Analysis

When you solve this algorithm in a technical interview (perhaps using a powerful platform like totop.app to practice!), the interviewer will inevitably ask about complexity:

  • Time Complexity: O(n). Although there is a nested while loop, each character in the string is visited at most twice (once by the right pointer to add it to the set, and optionally once by the left pointer to remove it). Thus, the time complexity is strictly linear, making it highly efficient.
  • Space Complexity: O(min(n, m)). We use a set to store characters. The size of the set is bounded by the size of the string n and the size of the character set/alphabet m (e.g., 26 for lowercase English letters, 128 for ASCII).

Takeaways for Your Coding Interview

The "Longest Substring Without Repeating Characters" problem is your gateway to mastering sliding window problems. Once you understand this pattern, you can tackle a vast array of similar array and string manipulation questions evaluated in top tech interviews.

To truly solidify this concept:

  1. Trace the code block above with the input s = "abcabcbb" on paper.
  2. Practice implementing it from scratch without looking at the solution.
  3. Try modifying the problem (e.g., longest substring with at most two distinct characters).

Ready to test your skills in a realistic interview environment? Make sure to structure your preparation and run through guided mock interviews. Preparing systematically is the best way to land your dream tech job!


Optimizing Sliding Window: Hash Set vs. Last-Seen Index Jump

Most candidates solve Longest Substring Without Repeating Characters using a Set and an inner while loop that increments left one step at a time whenever a duplicate character is encountered. While that runs in O(2n) = O(n) time, interviewers love asking: "Can you eliminate the inner while loop so left jumps directly past the duplicate in a single step?"

Implementation VariantWindow Shrink MechanismWorst-Case OperationsSpace Complexity
Brute ForceCheck all substrings with nested loopsO(n^3) or O(n^2)O(min(n, charset))
Sliding Window + HashSetIncrement left += 1 in a while loop removing chars2n operations (O(n))O(min(n, charset))
Sliding Window + Index Map (Optimal)Jump left = max(left, last_seen[char] + 1)Exactly n operations (O(n))O(min(n, charset))
Fixed 128-Element Integer ArrayDirect ASCII array lookup last_seen[ord(c)]O(n) with zero hash overheadO(1) (128 ints)

Why left = max(left, seen[char] + 1) Is the #1 Bug Spot

When jumping left directly to last_seen[char] + 1 without deleting older keys from the seen dictionary, seen may still contain characters from before the current left pointer! For example, on input "abba":

  • At index 2 ('b'), left jumps to index 2.
  • At index 3 ('a'), seen['a'] is still 0. If you write left = seen['a'] + 1 without max(left, ...), left would move backward from 2 to 1, falsely counting "bba" as unique! Wrapping the update in Math.max(left, ...) guarantees left is monotonically non-decreasing.

Common Interview Follow-Up: Longest Substring with At Most K Distinct Characters

Once you finish the base problem, interviewers frequently generalize the constraint: "Now find the longest substring that contains at most K distinct characters."

  • Replace the last-seen index map with a character frequency counter counts (or store the rightmost index of each character in the active window).
  • Expand right on every step, and whenever len(counts) > k, decrement counts[s[left]] (deleting the key when its count hits 0) and increment left += 1 until len(counts) <= k is restored. The base problem is simply the K-distinct template where the maximum allowed frequency per character is 1!
  • Unicode & Surrogate Pair Considerations: In JavaScript and Java, strings are UTF-16 code units, meaning emoji characters occupy two code units (a surrogate pair). Mentioning that iterating via Array.from(str) or for...of in JavaScript operates on full Unicode code points rather than raw 16-bit units is a strong senior signal.

Practice Full Stack Engineer Questions Live with AI Mock Interviews

Turn any job description across Engineering, DevOps, Data, Marketing, Sales, Finance, or HR into a personalized test and live voice or text AI mock interview on totop.app, or test your speed right now in the 60-Second Full Stack Engineer Blitz.

Play 60s Full Stack Engineer Blitz (Free, No Login) | Start 14-Day Free Trial | Browse All Interview Guides