C++ 0003.cpp
class Solution {
public:
int lengthOfLongestSubstring(string s) {
vector<bool> have(256, false);
int left = 0;
int maxx = 0;
for (int right = 0; right < s.size(); right++)
{
auto current = s[right];
if (have[current])
{
// shrink
while (s[left] != current)
have[s[left++]] = false;
left++;
}
// enlarge
have[current] = true;
if (maxx < right - left + 1)
maxx = right - left + 1;
}
return maxx;
}
};
Difficulty
and has an acceptance rate of about 40% (20+ million submissions).
Typical patterns to solve this problem:
- Hash Table
- Sliding Window
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the classic “longest substring without repeating characters” problem using a sliding-window technique. Two pointers, left and right, delimit the current window, while a fixed-size boolean array tracks which characters are present inside the window. As the right pointer advances through the input string, the algorithm expands the window when the new character is unseen and contracts it just enough to discard the previous occurrence when a duplicate appears. Throughout the scan, the length of the longest valid window is recorded and finally returned.
Initialization
At the start, a vector of 256 boolean flags is created, representing the full range of possible ASCII characters. All entries are set to false, indicating that no characters are currently inside the window. The left index is positioned at the beginning of the string, and maxx is initialized to zero to hold the best length found so far.
vector<bool> have(256, false);
int left = 0;
int maxx = 0;
Sliding Window Expansion
The main loop iterates with the right pointer from the first to the last character of the input string. For each iteration, the character at s[right] is stored in current. This character becomes the candidate for inclusion in the current window.
for (int right = 0; right < s.size(); right++) {
auto current = s[right];
// ...
}
If current has not been seen inside the window (have[current] is false), the algorithm proceeds directly to the enlargement step, marking the character as present.
have[current] = true;
Shrinking on Duplicate
When current is already flagged as present, a duplicate exists inside the window. The algorithm then moves the left pointer forward, clearing the have entries for each character it passes, until it reaches the previous occurrence of current. The loop condition s[left] != current ensures that characters are removed only up to, but not including, the duplicated character. After the loop, left is incremented once more to step past the duplicated character, guaranteeing that the new window contains no repeats.
if (have[current]) {
// shrink
while (s[left] != current)
have[s[left++]] = false;
left++;
}
Updating Maximum Length
After handling any necessary shrinking and marking the new character as present, the algorithm computes the size of the current window as right - left + 1. If this size exceeds the previously recorded maximum, maxx is updated accordingly.
if (maxx < right - left + 1)
maxx = right - left + 1;
Edge Cases Handled
The code gracefully manages several boundary conditions:
- An empty input string results in the loop body never executing, leaving
maxxat its initial value of zero, which correctly represents the length of the longest substring. - Strings consisting of a single character trigger the expansion path without ever entering the shrinking block, yielding a maximum length of one.
- When the entire string contains unique characters, the shrinking condition is never met, and the window continuously expands to cover the whole string, producing the full length as the result.
- For strings where the same character repeats consecutively, the shrinking loop removes the earlier occurrence and advances
leftpast it, ensuring that the window always starts at the most recent occurrence of that character.
Performance Optimizations
The implementation achieves high efficiency through several deliberate choices:
- The use of a fixed-size boolean vector eliminates the need for dynamic hash structures, providing constant-time access for character presence checks and updates.
- The sliding-window approach guarantees that each character index is visited at most twice: once when the
rightpointer includes it and once when theleftpointer discards it. This linear traversal avoids redundant scanning. - By moving
leftonly until the previous duplicate is removed, the algorithm avoids unnecessary clearing of characters that are already outside the current window, preserving the minimal amount of work required for each duplicate encounter. - The direct comparison
s[left] != currentinside the shrinking loop leverages the fact that the input string is stored contiguously, allowing fast character access without additional indirection.
Overall, the code presents a concise and effective solution that leverages a deterministic sliding window and a simple presence map to compute the desired length in a single pass over the input.
ELI5 - Simplified Explanation
Imagine you have a long string of colorful toy blocks lined up in a row. You want to pick a section of these blocks to hold in your hands, but there is one special rule. You are not allowed to hold two blocks that look exactly the same.
The code works like a little helper who walks past the line of blocks from left to right. It uses a sliding window to keep track of the blocks currently in your hands. A list called have acts as a checklist to see if a block is already in your hand or if it is brand new.
As the helper moves forward, the right side of the window grows to include a new block. If that block is already sitting in your hand, you have to start putting blocks back into the line from the left side until the repeating block is gone. This keeps your collection valid.
While the helper moves the window, it constantly checks how many blocks are currently being held. If the current group is bigger than the biggest group seen so far, the helper updates the record to remember this new, larger size. By the time the helper reaches the very end of the line, the record shows the largest number of blocks that were held together without any repeats.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||||||||
| WalkCCC | C++ | Python | Java | |||||||||||||
| leetcode.ca | C++ | Python | C# | Java | Rust | JS | Go | C | TS | Nim | PHP | Swift | ||||
| LeetcodeHelp | C++ | Python | Java | |||||||||||||
| MemoryLimitExceeded | C++ | Python | ||||||||||||||
| Progiez | C++ | Python | Java | |||||||||||||
| github | aylei | Rust | ||||||||||||||
| begeekmyfriend | C | |||||||||||||||
| BigEggStudy | C# | |||||||||||||||
| black-shadows | C++ | |||||||||||||||
| bujosa | Rust | |||||||||||||||
| chandansgowda | Python | |||||||||||||||
| charles-wangkai | Java | |||||||||||||||
| chenyanzhe | C++ | |||||||||||||||
| everthis | JS | |||||||||||||||
| fartem | Ruby | |||||||||||||||
| FelixFan1122 | C# | |||||||||||||||
| fengvyi | C++ | |||||||||||||||
| fsq | Python | |||||||||||||||
| gaosq0604 | Python | |||||||||||||||
| Garvit244 | Python | |||||||||||||||
| halfrost | Go | |||||||||||||||
| haoel | C++ | |||||||||||||||
| JoshCrozier | JS | |||||||||||||||
| keineahnung2345 | C++ | |||||||||||||||
| Krazune | C# | |||||||||||||||
| linouk23 | C++ | |||||||||||||||
| lkwq007 | Python | |||||||||||||||
| luangong | C++ | TS | ||||||||||||||
| muhammadfarhankt | Go | |||||||||||||||
| pruthvikp | Python | |||||||||||||||
| qiyuangong | Java | |||||||||||||||
| ruoru | Rust | |||||||||||||||
| Shamik07 | Dart | |||||||||||||||
| shreymehul | C# | |||||||||||||||
| sonugiri1043 | C++ | |||||||||||||||
| suxrobGM | C# | |||||||||||||||
| varunu28 | Java | |||||||||||||||
| vli02 | C | |||||||||||||||
| vthwang | Java | |||||||||||||||
| wisdompeak | C++ | |||||||||||||||
| XiaotaoGuo | C++ | |||||||||||||||
| yuanliu666 | Kotlin | |||||||||||||||
| YuriSpiridonov | Python | |||||||||||||||
| zfang399 | C++ | |||||||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||||||
| WalkCCC | C++, Python, Java | |||||||||||||||
| leetcode.ca | C, C++, C#, Go, Java, JavaScript, Nim, PHP, Python, Rust, Swift, TypeScript | |||||||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||||||
| Progiez | C++, Java, Python | |||||||||||||||
| aylei | Rust | |||||||||||||||
| begeekmyfriend | C | |||||||||||||||
| BigEggStudy | C# | |||||||||||||||
| black-shadows | C++, C++ | |||||||||||||||
| bujosa | Rust | |||||||||||||||
| chandansgowda | Python | |||||||||||||||
| charles-wangkai | Java | |||||||||||||||
| chenyanzhe | C++ | |||||||||||||||
| everthis | JavaScript | |||||||||||||||
| fartem | Ruby | |||||||||||||||
| FelixFan1122 | C# | |||||||||||||||
| fengvyi | C++ | |||||||||||||||
| fsq | Python | |||||||||||||||
| gaosq0604 | Python | |||||||||||||||
| Garvit244 | Python | |||||||||||||||
| halfrost | Go | |||||||||||||||
| haoel | C++ | |||||||||||||||
| JoshCrozier | JavaScript | |||||||||||||||
| keineahnung2345 | C++ | |||||||||||||||
| Krazune | C# | |||||||||||||||
| linouk23 | C++ | |||||||||||||||
| lkwq007 | Python | |||||||||||||||
| luangong | C++, TypeScript | |||||||||||||||
| muhammadfarhankt | Go | |||||||||||||||
| pruthvikp | Python | |||||||||||||||
| qiyuangong | Java | |||||||||||||||
| ruoru | Rust | |||||||||||||||
| Shamik07 | Dart | |||||||||||||||
| shreymehul | C# | |||||||||||||||
| sonugiri1043 | C++ | |||||||||||||||
| suxrobGM | C# | |||||||||||||||
| varunu28 | Java | |||||||||||||||
| vli02 | C | |||||||||||||||
| vthwang | Java | |||||||||||||||
| wisdompeak | C++ | |||||||||||||||
| XiaotaoGuo | C++ | |||||||||||||||
| yuanliu666 | Kotlin | |||||||||||||||
| YuriSpiridonov | Python | |||||||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 159: Longest Substring with At Most Two Distinct Characters
- problem 325: Maximum Size Subarray Sum Equals k
- problem 340: Longest Substring with At Most K Distinct Characters
- problem 992: Subarrays with K Different Integers
- problem 1695: Maximum Erasure Value
- problem 2260: Minimum Consecutive Cards to Pick Up
- problem 2401: Longest Nice Subarray
- problem 2405: Optimal Partition of String
- problem 2743: Count Substrings Without Repeating Character
- problem 2799: Count Complete Subarrays in an Array
- problem 2981: Find Longest Special Substring That Occurs Thrice I
- problem 2982: Find Longest Special Substring That Occurs Thrice II
Solved On The Same Day
- problem 1: Two Sum
- problem 9: Palindrome Number
- problem 14: Longest Common Prefix
- problem 20: Valid Parentheses
- problem 26: Remove Duplicates from Sorted Array
- problem 27: Remove Element
- problem 83: Remove Duplicates from Sorted List
- problem 88: Merge Sorted Array
- problem 94: Binary Tree Inorder Traversal
- problem 100: Same Tree
- problem 104: Maximum Depth of Binary Tree
- problem 121: Best Time to Buy and Sell Stock
- problem 136: Single Number
- problem 141: Linked List Cycle
- problem 169: Majority Element
- problem 190: Reverse Bits
- problem 226: Invert Binary Tree
- problem 234: Palindrome Linked List
- problem 1114: Print in Order
- problem 7: Reverse Integer
- problem 8: String to Integer (atoi)
- problem 11: Container With Most Water
- problem 12: Integer to Roman
- problem 15: 3Sum
- problem 17: Letter Combinations of a Phone Number
- problem 22: Generate Parentheses
- problem 31: Next Permutation
- problem 36: Valid Sudoku
- problem 39: Combination Sum
- problem 40: Combination Sum II
- problem 45: Jump Game II
- problem 46: Permutations
- problem 47: Permutations II
- problem 48: Rotate Image
- problem 49: Group Anagrams
- problem 55: Jump Game
- problem 59: Spiral Matrix II
- problem 75: Sort Colors
- problem 77: Combinations
- problem 91: Decode Ways
- problem 95: Unique Binary Search Trees II
- problem 96: Unique Binary Search Trees
- problem 134: Gas Station
- problem 164: Maximum Gap
- problem 189: Rotate Array
- problem 215: Kth Largest Element in an Array
- problem 238: Product of Array Except Self
- problem 287: Find the Duplicate Number
- problem 322: Coin Change
- problem 347: Top K Frequent Elements
- problem 377: Combination Sum IV
- problem 438: Find All Anagrams in a String
- problem 474: Ones and Zeroes
- problem 518: Coin Change II
- problem 526: Beautiful Arrangement
- problem 763: Partition Labels
- problem 983: Minimum Cost For Tickets
- problem 994: Rotting Oranges
- problem 1027: Longest Arithmetic Subsequence
- problem 2140: Solving Questions With Brainpower
- problem 2466: Count Ways To Build Good Strings
- problem 4: Median of Two Sorted Arrays
- problem 41: First Missing Positive
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality