Skip to content

Commit 85bb700

Browse files
committed
longest substring
1 parent 45cdf2a commit 85bb700

File tree

1 file changed

+39
-6
lines changed

1 file changed

+39
-6
lines changed

longest_substring_without_repeating_char.js

Lines changed: 39 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,18 +22,51 @@ And then push this char at this index position to the resetted-newSubStr value.
2222
C> And after all the above, at each iteration of the loop, we are reassigning the maxLen to be the max of maxLen till now and subArr.length. And by the end of all the iterations I am returning the final max.
2323
*/
2424

25-
var lengthOfLongestSubstring = function (s) {
25+
// SOLUTION-1
26+
var lengthOfLongestSubstring = function (s) {
27+
2628
let newSubStr = [], maxLen = 0, index;
2729

2830
for (let i = 0; i < s.length; i++) {
31+
2932
index = newSubStr.indexOf(s[i]);
33+
3034
if (index !== -1) {
31-
newSubStr = newSubStr.slice(index+1, newSubStr.length);
32-
}
35+
36+
newSubStr = newSubStr.slice(index+1); //Note, for slice() If endIndex is omitted, slice() extracts to the end of the string, when I want to extract / slice till the end of the string, I dont need to pass the second argument.
37+
}
38+
3339
newSubStr.push(s[i]);
34-
maxLen = Math.max(maxLen, newSubStr.length);
35-
}
40+
41+
maxLen = Math.max(maxLen, newSubStr.length);
42+
43+
}
44+
3645
return maxLen;
3746
}
3847

39-
console.log(lengthOfLongestSubstring("abcabcbb"));
48+
// console.log(lengthOfLongestSubstring("abcabcbb")); // => 3
49+
// console.log(lengthOfLongestSubstring("bbbbb")); // => 1
50+
// console.log(lengthOfLongestSubstring("pwwkew")); // => 3
51+
52+
// SOLUTION-2 - The same exact logic, only difference is, I am not using a separate variable index here. In the above I am first checking if this item is duplication (if duplicate then fist slice) and only then I am pushing to the newSubStr the char. But here, I am combining both these steps in below.
53+
54+
lengthOfLongestSubstring_2 = s => {
55+
56+
let max = 0, newSubStr = [];
57+
58+
for (let i = 0; i < s.length; i++) {
59+
60+
// If 'i' is duplicated newSubStr.indexOf(i) will return the current index of that i and I will start slicing from the next position. And if its not duplicated, I will staring slicing from 0-index position and all the way upto the last char of newSubStr.
61+
62+
newSubStr = newSubStr.slice(newSubStr.indexOf(s[i]) + 1)
63+
max = Math.max(newSubStr.push(s[i]), max); // remember the push() returns the new length of the array after pushing
64+
}
65+
return max;
66+
67+
}
68+
69+
70+
console.log(lengthOfLongestSubstring_2("abcabcbb")); // => 3
71+
console.log(lengthOfLongestSubstring_2("bbbbb")); // => 1
72+
console.log(lengthOfLongestSubstring_2("pwwkew")); // => 3

0 commit comments

Comments
 (0)