Leetcode 3. Longest Substring Without Repeating Characters
Given a string s
, find the length of the longest substring without repeating characters.
s
?
s
is between 0 and 5 * 10^4.s
only ASCII?
s
contains ASCII characters.The optimal approach to solve this problem is to use the sliding window technique along with a hash map to keep track of the characters and their indices within the current window. The sliding window will help us efficiently keep track of the longest substring without repeating characters by expanding and contracting as needed.
left
and right
) for the sliding window, both starting at the beginning of the string.right
pointer.
left
pointer right beyond the last occurrence of that character to ensure no repeating characters within the current window.#include <iostream>
#include <unordered_map>
#include <algorithm>
#include <string>
int lengthOfLongestSubstring(std::string s) {
std::unordered_map<char, int> charIndexMap;
int maxLength = 0;
int left = 0;
for (int right = 0; right < s.size(); ++right) {
if (charIndexMap.find(s[right]) != charIndexMap.end()) {
// Move left pointer to the right of the first occurrence of s[right]
left = std::max(charIndexMap[s[right]] + 1, left);
}
// Update the most recent index of s[right]
charIndexMap[s[right]] = right;
// Calculate the length of the current window
maxLength = std::max(maxLength, right - left + 1);
}
return maxLength;
}
// Test Example
int main() {
std::string s = "abcabcbb";
int length = lengthOfLongestSubstring(s);
std::cout << "Length of the longest substring without repeating characters: " << length << std::endl;
return 0;
}
The time complexity of this approach is O(n), where n
is the length of the string s
. This is because each character is processed at most twice (once by the right
pointer and once by the left
pointer). The space complexity is O(min(m, n)) for the hash map, where m
is the size of the character set, and n
is the length of the string s
. For ASCII characters, this is effectively O(1).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?