# How to find longest substring without repeating characters in a given string ?

4.38K views
0 Given a string, find the length of the longest substring without repeating characters.

Example 1:

Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.

Example 2:

Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

0

This problem follows a sliding window mechanism and can be easily solved by looping through the characters using indexes sliding over them

Javascript code below

/**
* @param {string} s
* @return {number}
*/
var lengthOfLongestSubstring = function(s) {
let windowStart = 0,
maxLength = 0,
charIndexMap = {};
for (let windowEnd = 0; windowEnd < s.length; windowEnd++) {
if (typeof charIndexMap[s[windowEnd]] !== 'undefined') {
windowStart = Math.max(windowStart, charIndexMap[s[windowEnd]]+1);
}
charIndexMap[s[windowEnd]] = windowEnd;
maxLength = Math.max(maxLength, windowEnd - windowStart + 1);
}
return maxLength;
};