
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.

Here is how we can apply the sliding window approach to our longest substring problem:
- Initialize Pointers: Create two pointers,
leftandright, both starting at the beginning of the string (index 0). - 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. - Expand the Window: Move the
rightpointer one step at a time.- If the character at
rightis not in our set, we add it, calculate the current window length (right - left + 1), and update our maximum length. - If the character at
rightis in our set, we have found a repeating character. We must now "shrink" the window from the left. We remove the character at theleftpointer from the set and incrementleft. We continue shrinking until the duplicate character is removed from the window.
- If the character at
- Repeat: Continue expanding and shrinking until the
rightpointer 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

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 nestedwhileloop, each character in the string is visited at most twice (once by therightpointer to add it to the set, and optionally once by theleftpointer 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 stringnand the size of the character set/alphabetm(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:
- Trace the code block above with the input
s = "abcabcbb"on paper. - Practice implementing it from scratch without looking at the solution.
- 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 Variant | Window Shrink Mechanism | Worst-Case Operations | Space Complexity |
|---|---|---|---|
| Brute Force | Check all substrings with nested loops | O(n^3) or O(n^2) | O(min(n, charset)) |
| Sliding Window + HashSet | Increment left += 1 in a while loop removing chars | 2n 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 Array | Direct ASCII array lookup last_seen[ord(c)] | O(n) with zero hash overhead | O(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'),leftjumps to index2. - At index
3('a'),seen['a']is still0. If you writeleft = seen['a'] + 1withoutmax(left, ...),leftwould move backward from2to1, falsely counting"bba"as unique! Wrapping the update inMath.max(left, ...)guaranteesleftis 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
righton every step, and wheneverlen(counts) > k, decrementcounts[s[left]](deleting the key when its count hits0) and incrementleft += 1untillen(counts) <= kis restored. The base problem is simply theK-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)orfor...ofin 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