Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Length Of Longest Substring Without Repeating Chars JS Solution #1064

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions Javascript/Longest_Substring_Without_Repeating_Characters.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// Problem Link: https://leetcode.com/problems/longest-substring-without-repeating-characters/

// Time Complexity - O(n)
// Space Complexity - O(n)

const lengthOfSubstring = (s) => {
//Return the length of string if it is less than or equal to 1
//as that would be the longest count
if (s.length <= 1) return s.length;

//Init values
//map - To keep track of chars we have seen
//left - To keep track of beginning of substring
//right - counter for our loop
//maxLength - maxSubstring Length
let map = {},
left = 0,
right = 0,
maxLength = 0;

//Go through loop till we get to end of string
while (right < s.length) {
//Get the value of the current character from the map
let currentIndex = map[s[right]];

//If it exists and is within our current substring
//set the left value to the character immediately after it
if (currentIndex !== undefined && currentIndex >= left) {
left = map[s[right]] + 1;
}

//Set value of character in map to its latest index
map[s[right]] = right;

//Set maxLength to the greater value between itself and the length of the current substring
maxLength = Math.max(maxLength, right - left + 1);

//Increase counter
right++;
}
return maxLength;
};