Created
November 13, 2024 12:10
-
-
Save sAVItar02/e10b35c011eb04d422d68c5d1c2e532e to your computer and use it in GitHub Desktop.
Longest Substring Without Repeating Characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {string} s | |
* @return {number} | |
*/ | |
var lengthOfLongestSubstring = function(s) { | |
let verifier = {}; | |
let i = 0; | |
let j = i+1; | |
let max = 1; | |
if(s.length == 0) return 0; | |
while(j < s.length) { | |
if(s[i] != s[j] && !verifier[s[j]]) { | |
verifier[s[j]] = s[j]; | |
max = Math.max(max, j-i + 1); | |
j++; | |
} else { | |
i++; | |
j = i+1; | |
verifier = {}; | |
} | |
} | |
return max; | |
}; | |
// Run a loop keeping 2 pointers, one at start (i) and the other at start + 1 (j) | |
// If the characters at current iterations not same and the character at j not in the object | |
// then add it to the object and increse j by 1 | |
// if any of these conditions fail, increase i by 1 and make j = i + 1 and empty the object | |
// return the max of i-j+1 and current max | |
// Time: O(n) | |
// Space: O(min(n, m)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment