Longest Substring Without Repeating Characters
Table of contents
3. Longest Substring Without Repeating Characters
Given a string s, find the length of the longest substring without
repeating characters.
Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
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.
Intuition
Maintain two pointers left and right. Iterate over array using right pointer. Keep inserting character at right into a map along with index.
If we encounter a duplicate character, move left to current character's index + 1 (or right + 1).
Calculate result as result = Math.max(result, right-left+1);
and keep track of it.
Visualisation
Code
class Solution {
public int lengthOfLongestSubstring(String s) {
int left=0, result=0;
Map<Character, Integer> map = new HashMap<>();
for(int right=0; right<s.length(); right++) {
char c = s.charAt(right);
if(map.containsKey(c)) {
left = Math.max(left, map.get(c) + 1);
}
map.put(c, right);
result = Math.max(result, right-left+1);
}
return result;
}
}
Learning
This problem expects us to know how to:
Iterate over array and use hash map
Use two pointers approach
Calculate substring length using formula (right - left + 1)
Handle corner case of