← Home

3. Longest Substring Without Repeating Characters

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
sliding windowC++Markdown
3

A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 3. Longest Substring Without Repeating Characters, the solution in this repository is mainly a sliding window solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: sliding window.

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are lengthOfLongestSubstring, allUnique, position.

Guide

Why?

The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.

  • A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
  • A set is doing the membership or uniqueness work, which keeps the main loop readable.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(N^3), space: O(min(size_of_string, size_of_charset))
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 84 ms, faster than 16.28% of C++ online submissions for Longest Substring Without Repeating Characters.
02//Memory Usage: 13.3 MB, less than 31.84% of C++ online submissions for Longest Substring Without Repeating Characters.
03class Solution {
04public:
05    int lengthOfLongestSubstring(string s) {
06        int ans = 0;
07        int start = 0, end = 0;
08        map<char, int> position;
09        
10        while(end < s.size()){
11            ans = max(ans, end-start+1);
12            position[s[end]] = end;
13            // cout << start << " " << end << endl;
14            // for(auto it = position.begin(); it != position.end(); it++){
15            //     cout << it->first << " " << it->second << " | ";
16            // }
17            // cout << endl;
18            if(end+1 < s.size()){
19                if(position.find(s[end+1]) == position.end()){
20                    end++;
21                }else{
22                    int newStart = position[s[end+1]]+1;
23                    for(int i = start; i < newStart; i++){
24                        position.erase(s[i]);
25                    }
26                    start = newStart;
27                    end++;
28                    // position.clear();
29                }
30            }else{
31                break;
32            }
33        }
34        
35        return ans;
36    }
37};
38
39//Brute Force
40//TLE
41//894 / 987 test cases passed.
42//time: O(N^3), space: O(min(size_of_string, size_of_charset))
43class Solution {
44public:
45    bool allUnique(string& s, int start, int end){
46        set<char> chars;
47        
48        for(int i = start; i <= end; i++){
49            auto res = chars.insert(s[i]);
50            if(res.second == false) return false;
51        }
52        
53        return true;
54    };
55    
56    int lengthOfLongestSubstring(string s) {
57        int ans = 0;
58        for(int i = 0; i < s.size(); i++){
59            for(int j = i; j < s.size(); j++){
60                if(allUnique(s, i, j)){
61                    ans = max(ans, j-i+1);
62                }
63            }
64        }
65        return ans;
66    }
67};
68
69//Approach 2: Sliding Window, using set
70//Runtime: 80 ms, faster than 16.88% of C++ online submissions for Longest Substring Without Repeating Characters.
71//Memory Usage: 13.4 MB, less than 30.85% of C++ online submissions for Longest Substring Without Repeating Characters.
72//time: O(N), space: O(min(size_of_string, size_of_charset))
73class Solution {
74public:
75    int lengthOfLongestSubstring(string s) {
76        int n = s.size();
77        set<char> chars;
78        int ans = 0, i = 0, j = 0;
79        while(i < n && j < n){
80            // cout << i << " " << j << endl;
81            if(chars.find(s[j]) == chars.end()){
82                //move head forward
83                chars.insert(s[j]);
84                ans = max(ans, j-i+1);
85                j++;
86            }else{
87                //move tail forward
88                chars.erase(s[i]);
89                i++;
90            }
91        }
92        
93        return ans;
94    }
95};
96
97//Approach 3: Sliding Window Optimized
98//Runtime: 44 ms, faster than 27.74% of C++ online submissions for Longest Substring Without Repeating Characters.
99//Memory Usage: 8.3 MB, less than 100.00% of C++ online submissions for Longest Substring Without Repeating Characters.
100//time: O(N), space: O(min(size_of_string, size_of_charset))
101class Solution {
102public:
103    int lengthOfLongestSubstring(string s) {
104        int n = s.size();
105        map<char, int> position;
106        int ans = 0;
107        
108        for(int i = 0, j = 0; j < n; j++){
109            if(position.find(s[j]) != position.end()){
110                i = max(i, position[s[j]]+1);
111            }
112            ans = max(ans, j-i+1);
113            position[s[j]] = j;
114        }
115        
116        return ans;
117    }
118};
119
120//Approach 4: Sliding Window Optimized, further optimized
121//Runtime: 8 ms, faster than 93.51% of C++ online submissions for Longest Substring Without Repeating Characters.
122//Memory Usage: 7.8 MB, less than 100.00% of C++ online submissions for Longest Substring Without Repeating Characters.
123//time: O(N), space: O(size_of_charset)
124class Solution {
125public:
126    int lengthOfLongestSubstring(string s) {
127        int n = s.size();
128        vector<int> position(128, -1);
129        int ans = 0;
130        
131        for(int i = 0, j = 0; j < n; j++){
132            if(position[s[j]] != -1){
133                i = max(i, position[s[j]]+1);
134            }
135            ans = max(ans, j-i+1);
136            position[s[j]] = j;
137        }
138        
139        return ans;
140    }
141};

Cost

Complexity

Time
O(N^3), space: O(min(size_of_string, size_of_charset))
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.