Longest Substring Without Repeating Characters
Given a string s, find the length of the longest substring without repeating characters.
Example:-
Input: s=abcabcbb
Output:3
Explanation: The answer is "abc", with a length of 3.
SOURCE CODE:
function lengthOfLongestSubstring(s) {
let maxLength = 0;
let left = 0;
const charIndexMap = {};
for (let right = 0; right < s.length; right++) {
const currentChar = s[right];
if (charIndexMap[currentChar] !== undefined &&
charIndexMap[currentChar] >= left) {
left = charIndexMap[currentChar] + 1;
}
charIndexMap[currentChar] = right;
const currentLength = right - left + 1;
maxLength = Math.max(maxLength, currentLength);
}
return maxLength;
}
// Test cases
console.log(lengthOfLongestSubstring("abcabcbb"));
// Output: 3
console.log(lengthOfLongestSubstring("bbbbb"));
// Output: 1
console.log(lengthOfLongestSubstring("pwwkew"));
// Output: 3