Appearance
Longest substring without repeating Medium
Question
Given a string s, find the length of the longest substring without repeating characters
txt
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
txt
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
txt
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
0 <= s.length <= 5 * 104
s consists of English letters, digits, symbols and spaces.
Solution
python
def length_of_longest_substring(s):
start = 0
max_length = 0
char_index_map = {} # Dictionary to store the last index of each character in the string
for i in range(len(s)):
if s[i] in char_index_map and char_index_map[s[i]] >= start:
start = char_index_map[s[i]] + 1
char_index_map[s[i]] = i
max_length = max(max_length, i - start + 1)
return max_length
# Test the function
s = "abcabcbb"
print(length_of_longest_substring(s)) # Output: 3 (the longest substring without repeating characters is "abc")
java
public class LongestSubstring {
public static int lengthOfLongestSubstring(String s) {
int start = 0;
int maxLength = 0;
Map<Character, Integer> charIndexMap = new HashMap<>(); // HashMap to store the last index of each character in the string
for (int i = 0; i < s.length(); i++) {
if (charIndexMap.containsKey(s.charAt(i)) && charIndexMap.get(s.charAt(i)) >= start) {
start = charIndexMap.get(s.charAt(i)) + 1;
}
charIndexMap.put(s.charAt(i), i);
maxLength = Math.max(maxLength, i - start + 1);
}
return maxLength;
}
public static void main(String[] args) {
String s = "abcabcbb";
System.out.println(lengthOfLongestSubstring(s)); // Output: 3 (the longest substring without repeating characters is "abc")
}
}
javascript
function lengthOfLongestSubstring(s) {
let start = 0;
let maxLength = 0;
const charIndexMap = new Map(); // Map to store the last index of each character in the string
for (let i = 0; i < s.length; i++) {
if (charIndexMap.has(s[i]) && charIndexMap.get(s[i]) >= start) {
start = charIndexMap.get(s[i]) + 1;
}
charIndexMap.set(s[i], i);
maxLength = Math.max(maxLength, i - start + 1);
}
return maxLength;
}
// Test the function
const s = "abcabcbb";
console.log(lengthOfLongestSubstring(s)); // Output: 3 (the longest substring without repeating characters is "abc")
Notes
We will use a sliding window approach to solve this problem. The idea is to maintain a window of characters in the string such that all characters within the window are unique. We will keep track of the start index and end index of the window and use a data structure (HashMap/Dictionary) to store the last index of each character seen so far. As we move through the string, we will update the window and the data structure to maintain the uniqueness of characters within the window.
Algorithm:
- Initialize two variables
start
andmax_length
to 0. These will keep track of the start index of the current window and the maximum length of the substring without repeating characters found so far. - Create an empty HashMap/Dictionary named
char_index_map
. This data structure will store the last index at which each character was seen in the string. - Iterate through the input string
s
using a loop and maintain an index variablei
to traverse each character in the string. - Inside the loop, do the following: a. If the current character
s[i]
is present in thechar_index_map
, and its last index is greater than or equal to thestart
index, it means the character is repeating within the current window. In this case, update thestart
index to the next index after the last occurrence of the character. b. Update thechar_index_map
with the current character and its index, as we have seen it at positioni
. c. Update themax_length
by taking the maximum of the currentmax_length
and the length of the current window, i.e.,i - start + 1
. - Continue this process until all characters in the string have been processed.
- The final
max_length
will be the length of the longest substring without repeating characters.