LeetCode 3: Longest Substring Without Repeating Characters is a Medium sliding window problem. This Python walkthrough develops a last-seen sliding window solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.
This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.
| Difficulty | Medium |
|---|---|
| Topic | Sliding Window |
| Reusable pattern | last-seen sliding window |
| Complexity | O(n) time and O(k) space |
Recognizing the pattern
A sliding window fits when validity changes incrementally as the right edge expands and the left edge contracts.
For this problem specifically, track each character’s latest index and move the left boundary past a repeated occurrence when it lies inside the current window. The invariant worth writing beside the code is: The active window contains no duplicate characters.
Step-by-step algorithm
- Identify the input state consumed by
lengthOfLongestSubstring(s)and initialize the data required by the last-seen sliding window pattern. - Track each character’s latest index and move the left boundary past a repeated occurrence when it lies inside the current window.
- After each update, verify the page’s central invariant: The active window contains no duplicate characters.
- Finish only after the boundary behavior is covered: The repeated character may have occurred before the current window and should then be ignored.
Python solution
class Solution:
def lengthOfLongestSubstring(self, s):
last = {}; left = best = 0
for right, char in enumerate(s):
if char in last and last[char] >= left: left = last[char] + 1
last[char] = right
best = max(best, right - left + 1)
return bestReading the implementation
The main entry point is lengthOfLongestSubstring(s). The named working state includes last, best; those variables make the last-seen sliding window state visible instead of hiding it in incidental control flow.
A single main loop advances the algorithm, which is the key reason the traversal does not revisit already resolved input unnecessarily. In concrete terms, track each character’s latest index and move the left boundary past a repeated occurrence when it lies inside the current window.
Correctness argument
Initialization. Before the scan begins, the unresolved range contains every candidate and the processed range is empty, so no answer has been lost.
Preservation. Track each character’s latest index and move the left boundary past a repeated occurrence when it lies inside the current window. The chosen movement discards only candidates that cannot improve the answer; afterward, the active window contains no duplicate characters.
Termination. A boundary advances on every iteration. Once the active range is exhausted, every viable candidate was either measured or safely eliminated, so the stored result is optimal.
Complexity and trade-offs
O(n) time and O(k) space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.
Enumerating every substring or subarray is conceptually simple but recomputes almost the same state for overlapping ranges. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.
Regression check
The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.
One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.
assert Solution().lengthOfLongestSubstring("abcabcbb") == 3Common mistakes and edge cases
- Problem-specific boundary: The repeated character may have occurred before the current window and should then be ignored.
- Pattern-level pitfall: Update counts in the correct order when an item enters or leaves, especially when duplicate requirements are present.
- Invariant check: after every update, confirm that the active window contains no duplicate characters.
Interview review checklist
- Explain why last-seen sliding window matches the structure of this input.
- State the invariant in one sentence before tracing code: The active window contains no duplicate characters.
- Derive O(n) time and O(k) space from how many times each element or state is visited.
- Test the boundary explicitly: The repeated character may have occurred before the current window and should then be ignored.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 209. Minimum Size Subarray Sum · Next: 30. Substring with Concatenation of All Words