Problem 3

Abstract / Summary

Find the length of the longest string section with all unique characters.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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;
    }
};
28 lines | 663 bytes | submitted August 8, 2023 | GitHub   9% comment ratio | tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 40% (20+ million submissions).

Typical patterns to solve this problem:
  • Hash Table
  • Sliding Window
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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 maxx at 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 left past 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 right pointer includes it and once when the left pointer discards it. This linear traversal avoids redundant scanning.
  • By moving left only 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] != current inside 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 30 | median = 8 | μ = 7.63 | σ = 0.55

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
67 links | 45 authors | 15 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Longest Substring Without Repeating Characters - Leetcode 3 - Python'
NeetCode 7 mins
Longest Substring Without Repeating Characters - Leetcode 3 - Python
YouTube video 'Longest Substring Without Repeating Characters - Leetcode 3 - Python'
NeetCode 7 mins
Longest Substring Without Repeating Characters - Leetcode 3 - Python
YouTube video 'Leetcode 3. Longest Substring Without Repeating Characters'
Code with Alisha 16 mins
Leetcode 3. Longest Substring Without Repeating Characters
YouTube video 'Longest Repeating Substring without repeating characters (LeetCode 3) | Two pointer approach'
Nikhil Lohia 18 mins
Longest Repeating Substring without repeating characters (LeetCode 3) | Two pointer approach
YouTube video 'Longest Substring Without Repeating Characters - Leetcode 3 - Sliding Window (Python)'
Greg Hogg 13 mins
Longest Substring Without Repeating Characters - Leetcode 3 - Sliding Window (Python)
YouTube video 'LeetCode 3: Longest Substring Without Repeating Characters'
Algo Engine 9 mins
LeetCode 3: Longest Substring Without Repeating Characters
YouTube video 'LeetCode 3 Solution in Hindi | Longest Substring Without Repeating Characters | LeetCode Playlist'
Engineering Digest 12 mins
LeetCode 3 Solution in Hindi | Longest Substring Without Repeating Characters | LeetCode Playlist
YouTube video 'Longest Substring Without Repeating Characters | LeetCode 3 | Coding Interview Tutorial'
Terrible Whiteboard 18 mins
Longest Substring Without Repeating Characters | LeetCode 3 | Coding Interview Tutorial
YouTube video 'Longest Substring Without Repeating Characters - LeetCode 3 Python'
Deepti Talesra 11 mins
Longest Substring Without Repeating Characters - LeetCode 3 Python
YouTube video 'Longest Substring Without Repeating Characters | Live Coding with Explanation | Leetcode - 3'
Algorithms Made Easy 8 mins
Longest Substring Without Repeating Characters | Live Coding with Explanation | Leetcode - 3
YouTube video 'Longest Substring Without Repeating Characters - LeetCode 3 - JavaScript'
AlgoJS 7 mins
Longest Substring Without Repeating Characters - LeetCode 3 - JavaScript
YouTube video 'Longest Substring Without Repeating Characters Python Solution - LeetCode #3'
Professor Oakes 6 mins
Longest Substring Without Repeating Characters Python Solution - LeetCode #3
YouTube video 'Longest Substring Without Repeating Characters | Leet code 3 | Theory explained + Python code'
Sai Anish Malla 18 mins
Longest Substring Without Repeating Characters | Leet code 3 | Theory explained + Python code
YouTube video 'Leetcode | 3. Longest Substring Without Repeating Characters | Medium | Java Solution'
Developer Docs 12 mins
Leetcode | 3. Longest Substring Without Repeating Characters | Medium | Java Solution
YouTube video 'DSA Phir se with Sumeet | Leetcode 3 | Longest Substring Without Repeating Characters'
Pepcoding 31 mins
DSA Phir se with Sumeet | Leetcode 3 | Longest Substring Without Repeating Characters
YouTube video 'Longest Substring Without Repeating Characters - LeetCode 3 - Sliding Window'
One Code Man 7 mins
Longest Substring Without Repeating Characters - LeetCode 3 - Sliding Window
YouTube video '[Java] Leetcode 3. Longest Substring Without Repeating Characters [Sliding Windows #3]'
Eric Programming 13 mins
[Java] Leetcode 3. Longest Substring Without Repeating Characters [Sliding Windows #3]
YouTube video 'Longest Substring Without Repeating Characters | LeetCode 3 | Two Pointer'
Naresh Gupta 15 mins
Longest Substring Without Repeating Characters | LeetCode 3 | Two Pointer
YouTube video 'Longest Substring Without Repeating Characters (LeetCode 3) | 🔥 DSA Java Placement Course'
Smart Programming 22 mins
Longest Substring Without Repeating Characters (LeetCode 3) | 🔥 DSA Java Placement Course
YouTube video 'Longest Substring Without Repeating Characters - 3. LeetCode - C#'
Teddy Smith 8 mins
Longest Substring Without Repeating Characters - 3. LeetCode - C#
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

12 similar problems

Solved On The Same Day

19 easy 42 medium 2 hard
64 solutions   August 8, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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