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 e36ab53

Browse files
Add alternate solution to 03 problem
1 parent 51b9706 commit e36ab53

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

‎Algo-Patterns/sliding-window-pattern/03-longest-substr-with-k-distinct-char.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,39 @@ console.log(longest_substring_with_k_distinct("araaci", 2));
5454
console.log(longest_substring_with_k_distinct("araaci", 1));
5555
console.log(longest_substring_with_k_distinct("cbbebi", 3));
5656

57+
// --------- Alternate Solution using while loop the overall concept is same. ------------
58+
59+
function longest_substring_with_k_distinct_01(str, k) {
60+
let j = 0;
61+
let i = 0;
62+
const hashMap = {};
63+
let longestLength = 0;
64+
65+
while(j < str.length) {
66+
if (hashMap.hasOwnProperty(str[j])) {
67+
hashMap[str[j]]++;
68+
} else {
69+
hashMap[str[j]] = 1;
70+
}
71+
72+
j++;
73+
74+
while(Object.keys(hashMap).length > k) {
75+
hashMap[str[i]]--;
76+
if (hashMap[str[i]] === 0) {
77+
delete hashMap[str[i]];
78+
}
79+
80+
i++;
81+
};
82+
83+
longestLength = Math.max(longestLength, j - i); // Not addding "+1" because I incremented j (j++) before inner while loop. If you increment j (j++) after inner while loop caclulate longestLength like this: `Math.max(longestLength, j - i + 1)`.
84+
};
85+
86+
return longestLength;
87+
};
88+
89+
5790
/*
5891
Time Complexity #
5992
The time complexity of the above algorithm will be O(N)O(N) where ‘N’ is the number of characters in the input string. The outer for loop runs for all characters and the inner while loop processes each character only once, therefore the time complexity of the algorithm will be O(N+N)O(N+N) which is asymptotically equivalent to O(N)O(N).

0 commit comments

Comments
(0)

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