From 4914bc3f79904ae8eca27db431ea9c4e2b480b20 Mon Sep 17 00:00:00 2001 From: Seun Taiwo Date: Wed, 13 Oct 2021 21:50:18 +0100 Subject: [PATCH 1/2] Added js solution for longest substring without repeating chars --- ..._Substring_Without_Repeating_Characters.js | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Javascript/Longest_Substring_Without_Repeating_Characters.js diff --git a/Javascript/Longest_Substring_Without_Repeating_Characters.js b/Javascript/Longest_Substring_Without_Repeating_Characters.js new file mode 100644 index 0000000..0e9ede4 --- /dev/null +++ b/Javascript/Longest_Substring_Without_Repeating_Characters.js @@ -0,0 +1,40 @@ +// 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; +}; From b55ac71de3d3c92e4a85cd2de045241c2f7e705f Mon Sep 17 00:00:00 2001 From: Seun Taiwo Date: Wed, 13 Oct 2021 21:52:55 +0100 Subject: [PATCH 2/2] Added Question Link --- Javascript/Longest_Substring_Without_Repeating_Characters.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Javascript/Longest_Substring_Without_Repeating_Characters.js b/Javascript/Longest_Substring_Without_Repeating_Characters.js index 0e9ede4..ac2894d 100644 --- a/Javascript/Longest_Substring_Without_Repeating_Characters.js +++ b/Javascript/Longest_Substring_Without_Repeating_Characters.js @@ -1,3 +1,5 @@ +// Problem Link: https://leetcode.com/problems/longest-substring-without-repeating-characters/ + // Time Complexity - O(n) // Space Complexity - O(n)