Skip to content

Instantly share code, notes, and snippets.

@sAVItar02
Created November 13, 2024 12:10
Show Gist options
  • Save sAVItar02/e10b35c011eb04d422d68c5d1c2e532e to your computer and use it in GitHub Desktop.
Save sAVItar02/e10b35c011eb04d422d68c5d1c2e532e to your computer and use it in GitHub Desktop.
Longest Substring Without Repeating 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