Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit b53fb7d

Browse files
Fix wrong solution of 05 problem
1 parent d822368 commit b53fb7d

File tree

1 file changed

+63
-3
lines changed

1 file changed

+63
-3
lines changed

‎Algo-Patterns/sliding-window-pattern/05-non-repeating-substr.js

Lines changed: 63 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,9 +42,69 @@ function non_repeat_substring(str) {
4242
return maxLength;
4343
}
4444

45-
console.log(non_repeat_substring("aabccbb"));
46-
console.log(non_repeat_substring("abbbb"));
47-
console.log(non_repeat_substring("abccde"));
45+
// console.log(non_repeat_substring("aabccbb"));
46+
// console.log(non_repeat_substring("abbbb"));
47+
// console.log(non_repeat_substring("abccde"));
48+
console.log(non_repeat_substring("abcdaefghijkl"), "#0");
49+
50+
// -------- Alternate Solution ----------
51+
// The above solution algo fails for last testcase. The 2 solutions below are correct.
52+
53+
// Solution 1
54+
function noRepeatCharLen1(str) {
55+
let j = 0;
56+
let i = 0;
57+
const frequencyTracker = {};
58+
let longestSubStrLen = 0;
59+
60+
while(j < str.length) {
61+
if (!frequencyTracker.hasOwnProperty(str[j])) {
62+
frequencyTracker[str[j]] = 1;
63+
longestSubStrLen = Math.max(longestSubStrLen, j - i + 1);
64+
} else {
65+
frequencyTracker[str[j]]++;
66+
}
67+
68+
while(frequencyTracker[str[j]] > 1) {
69+
frequencyTracker[str[i]]--
70+
if (frequencyTracker[str[i]] === 0) {
71+
delete frequencyTracker[str[i]];
72+
}
73+
74+
i++;
75+
}
76+
77+
j++;
78+
};
79+
80+
return longestSubStrLen;
81+
}
82+
83+
// Solution #2
84+
function noRepeatCharLen2(str) {
85+
let windowStart = 0,
86+
maxLength = 0,
87+
charIndexMap = {};
88+
89+
for(let windowEnd = 0; windowEnd < str.length; windowEnd++) {
90+
const rightChar = str[windowEnd];
91+
92+
if (rightChar in charIndexMap) {
93+
windowStart = Math.max(windowStart, charIndexMap[rightChar] + 1);
94+
}
95+
96+
charIndexMap[rightChar] = windowEnd;
97+
98+
maxLength = Math.max(maxLength, windowEnd - windowStart + 1);
99+
}
100+
101+
return maxLength;
102+
}
103+
104+
console.log(noRepeatCharLen1("abcdaefghijkl"), "#1");
105+
console.log(noRepeatCharLen2("abcdaefghijkl"), "#2");
106+
107+
// a b c d a e f g h i j k l
48108

49109
/*
50110
Time Complexity #

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /