Skip to content

Instantly share code, notes, and snippets.

@headquarters
Created June 11, 2022 18:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save headquarters/ac056635cd44671b0a449bf2ca73e87e to your computer and use it in GitHub Desktop.
Save headquarters/ac056635cd44671b0a449bf2ca73e87e to your computer and use it in GitHub Desktop.
Sliding window in TypeScript
// Find the longest length of a substring without repeating characters, e.g. "abcabc" => 3
function lengthOfLongestSubstring(s: string): number {
let n = s.length;
let longest = 0;
let nextIndex = [];
for (let right = 0, left = 0; right < n; right++) {
left = Math.max(nextIndex[s.charAt(right)] || 0, left);
longest = Math.max(longest, right - left + 1);
nextIndex[s.charAt(right)] = right + 1;
}
return longest;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment