Longest Substring Without Repeating Characters: A Classic Sliding Window Problem in Python

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 nested
whileloop, 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 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:
- 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!