Longest Substring With K Unique Characters | Variable Size Sliding Window

  Рет қаралды 165,817

Aditya Verma

Aditya Verma

Күн бұрын

Пікірлер: 405
@_insanebuddy
@_insanebuddy 2 жыл бұрын
First time,I m feeling confident to solve questions related to subarray .I m really blessed to find your channel.Thankyou so much sir!
@MiraclePlayzzzz
@MiraclePlayzzzz 4 жыл бұрын
Lets vote for Backtracking
@ayushyadav4180
@ayushyadav4180 3 жыл бұрын
koi faida nhi aditya verma bebafa hai XD
@hamidansari9331
@hamidansari9331 3 жыл бұрын
Sahi kha
@AnkitSingh-wq2rk
@AnkitSingh-wq2rk 3 жыл бұрын
@@raviashwin1157 free mein karrha hai usme bhi dikkat lmao
@helloworld0509
@helloworld0509 3 жыл бұрын
Moon-policy kahte hai shayad
@gunjakumari1951
@gunjakumari1951 2 жыл бұрын
Yep
@divyranjan254
@divyranjan254 3 жыл бұрын
Instead of erasing each entry when it gets 0 we can also use the approach he has used for count of anagrams. The idea of storing a count of distinct characters is a really useful one whenever we want to get an idea of characters to be taken into account WITHOUT acutally travelling the map or making some modifications.
@davendrabedwal830
@davendrabedwal830 Жыл бұрын
Here's what you were thinking of: int longestKSubstr(string s, int k) { int n=s.size(); unordered_mapm; int i=0; int j=0; int dist=0; int ans=-1; while(j
@abdussamad0348
@abdussamad0348 Жыл бұрын
You meant this approach const str = 'aabbvxbbc'; function longestSubstringWithKUniqueChar(str, k) { let [start, end, res, count, obj] = [0, 0, 0, 0, {}]; while (end < str.length) { if (!obj.hasOwnProperty(str[end])) { count++ } obj[str[end]] = (obj[str[end]] || 0) + 1; if (count > k) { while (count > k) { obj[str[start]] = obj[str[start]] - 1; if (obj[str[start]] === 0) { delete obj[str[start]]; count-- } start++; } } if (count === k) { res = Math.max(res, end - start + 1); } end++ } return res }
@ashrafsir69
@ashrafsir69 Жыл бұрын
After watching all the previous 9 videos, I am so happy that I was able to solve this problem all by myself. I followed the exact approach that you take while you solve the problems while explaining them in video. Thanks a lot dude. I had been struggling with DSA for quite some time now and finally I feel confident and all thanks to these videos of yours.
@imPriyansh77
@imPriyansh77 Жыл бұрын
Same here ! Thanks
@rvr61
@rvr61 3 жыл бұрын
Please make a series for the XOR problems. We always see various tricky problems in contests. It will be very helpful.
@letscode8697
@letscode8697 2 жыл бұрын
ek hi solution he bro "PRACTICE" aur kuch nai hone vala
@swarbhatia
@swarbhatia 5 ай бұрын
I just watched the first few lectures regarding the idea behind fixed size and variable size sliding window, and now i am solving problems on my own without checking the video out! Really helpful! Here is my implementation for the above question: simply applied the variable window template and used a frequency array to keep a track of the occurrences of each character. int longestKSubstr(string s, int k) { int n=s.size(); int i=0;int j=0; vector freq(27,0); int ans=-1; while(jk){ freq[s[i]-'a']--; if(freq[s[i]-'a']==0){ count--; } i++; } j++; } return ans; }
@ankitkumarpathak6768
@ankitkumarpathak6768 2 жыл бұрын
i have solved this question on my own by just seen the video title and start doing solveing Amazing part is that i have written exactly same code(word to word) as @Aditya sir .This shows the effort of aditya sir that how he explain in previous videos again and again, hats off to you sir
@roct07
@roct07 3 жыл бұрын
Managed to solve this problem without looking at the video because of the previous videos. Thanks for such an awesome playlist 🙌
@divyranjan254
@divyranjan254 3 жыл бұрын
same :)
@rishabhgupta9846
@rishabhgupta9846 Жыл бұрын
same here
@4mulate
@4mulate 7 ай бұрын
same here :D
@kanakmittal3756
@kanakmittal3756 3 жыл бұрын
Was able to solve this problem without even watching the video. Thank You so much.
@349_rahulbhattacharya6
@349_rahulbhattacharya6 3 жыл бұрын
For future visitors here...This is the best explanation and playlist for this question and sliding window questions you need not to go anywhere else ...thora lengthy hai but dhyan dena coz dhyan hata toh smjh nhi aayega phir..myself watched this 3 times due to phone distraction :(( ..Aditya bhaiya you are best!!..Hopefully i get placed in a decent/good company ...
@prathamanand1037
@prathamanand1037 2 жыл бұрын
Mili koi company ?
@kartiksrivastava3897
@kartiksrivastava3897 2 жыл бұрын
@@prathamanand1037 same question
@sahildalal1368
@sahildalal1368 2 жыл бұрын
@@prathamanand1037 hnn trilogy xD
@lex-zt6uc
@lex-zt6uc 2 жыл бұрын
@@sahildalal1368 😂😂
@deepakffyt2844
@deepakffyt2844 2 жыл бұрын
@@kartiksrivastava3897 same question
@your_name96
@your_name96 2 жыл бұрын
a bit extended shorter version, but understanding of the exhaustive version is must mapmp; int cnt = 0; int start=0, end = 0; int ans = -1; while(end < s.size()){ mp[s[end]]++; // distinct count check after add if(mp[s[end]] == 1){ cnt++; } while(cnt > k){ mp[s[start]]--; // distinct count count after remove if(mp[s[start]]==0){ cnt--; } start++; } if(cnt == k){ ans = max(ans, end-start+1); } end++; } return ans;
@misterdi7238
@misterdi7238 Жыл бұрын
thanks bro
@CosmosHole
@CosmosHole 5 ай бұрын
is this code accepting all testcases, i tried it doesn't?
@pprathameshmore
@pprathameshmore 2 жыл бұрын
You are one of the best teacher ever met for understanding these interview questions!
@ganeshkosimala8031
@ganeshkosimala8031 Жыл бұрын
2 mins into the video coded it myself .Awesome explanation sir
@mayanktyagi8051
@mayanktyagi8051 14 күн бұрын
Able to solve it without looking to solution. What a great explanation. Feeling confident in sliding window problems.
@b_01_aditidonode43
@b_01_aditidonode43 Жыл бұрын
thanks sir, you explained the variable sliding format so well that I was able to solve the question on my own..
@ahdiviomendes4763
@ahdiviomendes4763 Жыл бұрын
this is the best I have ever seen some one explain this please continue this I was struggling for so long with sliding windows thank you
@alokgautam859
@alokgautam859 2 жыл бұрын
bhai bht hi accha smjhaya hai mai apne bootcamp me ise acche se smjh nhi paa rha tha but after watching your all video i feel much confident
@aptitudepointiit-bhu5358
@aptitudepointiit-bhu5358 2 жыл бұрын
Awesome lecture as always. if(hsh.size()==k) maxAns = max(maxAns, j-i+1); Also add the above line (before the ending of the third case), to be on the safer side.
@PIYUSH-lz1zq
@PIYUSH-lz1zq 2 жыл бұрын
bro
@sayantaniguha8519
@sayantaniguha8519 2 жыл бұрын
Don't understand how it works even without this
@ishangujarathi10
@ishangujarathi10 Жыл бұрын
amazing intuition!!!! it was a hard question, which was asked in google interviews as per gfg!!! tysm for the explanation and crystal clear approach
@tekbssync5727
@tekbssync5727 3 жыл бұрын
starting 5s and ending 5s. Booster sound fills me with 200% energy 🧡😁
@anshulpandey6576
@anshulpandey6576 3 жыл бұрын
absolutely true.......
@A_WAY_TO_BETTER_LIFE
@A_WAY_TO_BETTER_LIFE 5 ай бұрын
one week ago, I studied the sliding window algo and then solved 2-3 some easy ques of this algo but when i tried to solve a medium ques , i was not able to solve then i searched that problem in youtube and i found this video but before watching the sol of that problem , i prefered to watch your sliding window playlist first , and now after 3-4 days i solved this problem without watching the complete solution. ☺thanks a lot sir ❣
@navneetshree9133
@navneetshree9133 2 жыл бұрын
Java Code for the question: Approach: 1. Keep on building the substring from j=0 [increasing the window size] and log occurance of each character in a Map. 2. If map size (Unique Characters in Map) becomes greater than k, keep on reducing window size (increase i pointer) and decrease the occurance of character from Map till map size becomes
@imPriyansh77
@imPriyansh77 Жыл бұрын
correct, thanks
@akashpurbia4390
@akashpurbia4390 11 ай бұрын
Able to solve the problem before starting this video using prev concepts - count occurence of anagrams. int longestKSubstr(string s, int k) { // your code here //We have identified that this problem is of Variable size sliding window //string, substring, return window size with a given condition(window should contain k unqiue character and it should be //longest) //Here we can use hashmap to store the occurences of each characters unordered_map mp; int i=0, j=0; //for traversing the string int mx = -1; // will store the longest substring with k unique characters int count=0; //this variale will be used as to maintain our condition to find the mx int n = s.size(); while(j
@radium990
@radium990 2 ай бұрын
Thanks boi🎉🎉🎉
@radium990
@radium990 2 ай бұрын
Rajasthan se ho? Bhaya?
@akashpurbia4390
@akashpurbia4390 2 ай бұрын
​@@radium990Yess
@abrahamlincoln5724
@abrahamlincoln5724 2 жыл бұрын
Instead of using a map to count the occurrence of a character, we could use an array of size 26 and increase the count of the visited character. Space complexity would be constant even if the input string size becomes large. (Correct me if I am wrong, I am learning so any correction would be appreciated). In the count array, if we are visiting the character first time (if the count of that char is 0), then we could increase the unique chars counter. If the counter > k, decrease the char count of left most char. If the char count of left most is 0, we decrement the counter by 1.
@sarthak7839
@sarthak7839 2 жыл бұрын
yes you can do it but using the map will reduce the time of writing so much of code for arrays
@user-le6ts6ci7h
@user-le6ts6ci7h Жыл бұрын
Even for map , your space is optimised as much as keeping an array of length 26
@parthmittal5625
@parthmittal5625 3 жыл бұрын
True power of teaching is when your student solves the question only by watching the previous questions! 😉
@ranjeetsinghbhati5540
@ranjeetsinghbhati5540 Жыл бұрын
// Longest Substring k unique character /* Given a string you need to print the size of the longest possible substring that has exactly k unique characters. Example: Input: 2 aabacbebebe 3 aaaa 1 Output: 7 4 . */ #include using namespace std; int longest(string str,int k){ int i=0,j=0; int maxi=INT_MIN; int count=0; unordered_map map; map.clear(); while(jk){ map[str[i]]--; if(map[str[i]]==0){ map.erase(str[i]); } i++; } j++; } } return maxi; } int main() { string str; cin>>str; int k; cin>>k; cout
@imPriyansh77
@imPriyansh77 Жыл бұрын
Shouldn't there be an 'if' condition if(map.size() == k){ maxi = max(maxi, j - i + 1) after the i++ in the last 'else-if' condition ? Like this :------ #include #include #include using namespace std; int longestSubstr(string s, int k) { int i = 0, j = 0, maxlen = INT_MIN; unordered_map mp; while (j < s.length()) { // Calculations mp[s[j]]++; int count = mp.size(); // Condition if (count < k) { j++; } else if (count == k) { maxlen = max(maxlen, j - i + 1); j++; } else { while (count > k) { mp[s[i]]--; if (mp[s[i]] == 0) { mp.erase(s[i]); } i++; if (count == k) { maxlen = max(maxlen, j - i + 1); } } j++; } } return maxlen; } int main() { string str = "aabacbebebe"; int k = 3; cout
@noneedtoknowthishandle
@noneedtoknowthishandle 10 ай бұрын
By using for loop we will be able to get rid of those if condition. one which includes condition == k and another for condition < k.
@deepaknegi6597
@deepaknegi6597 2 ай бұрын
thanks sir to built my confidence how to convert approach in a language
@LokeshSharma-hm5jz
@LokeshSharma-hm5jz Жыл бұрын
The format you provided and explained allow me to solve this question myself.. Thanks a lot;
@AyushAgrawal-qm1tr
@AyushAgrawal-qm1tr Жыл бұрын
I am so happy to solve this without watching the solution. Thank you for this amazing series.
@momentumbees3433
@momentumbees3433 2 жыл бұрын
I added a check for if the no of unique chars in the string is less than the k.. for example Str=aaabe k =4 HashMap charMap=new HashMap(); int i =0; int j =0; int maxStringlen = Integer.MIN_VALUE; while(jk){ if(charMap.containsKey(s.charAt(i))){ int freq=charMap.get(s.charAt(i)); freq--; charMap.put(s.charAt(i),freq); } if(charMap.get(s.charAt(i))==0){ charMap.remove(s.charAt(i)); } i++; } j++; } } System.out.println("The no of unique chars are : " + charMap.size()); return (charMap.size()
@shlokhinge3179
@shlokhinge3179 4 жыл бұрын
Legend is back🔥 Btw ,Your old into music was fab ..!! Plz Continue with it🙏😁
@sonianarendramodi2605
@sonianarendramodi2605 2 жыл бұрын
@@ujjawal.pandey lol
@abhilashasaini8758
@abhilashasaini8758 4 жыл бұрын
Your channel is soo underrated.. Thankyou for such quality content
@teksomegeek2062
@teksomegeek2062 3 жыл бұрын
In GFG, just take max=-1, rest everything Adi sir has taught is correct.
@rudradevvlogs9894
@rudradevvlogs9894 Жыл бұрын
Farishte ho tum bhai 😂 Btw , thanks for this hint
@anjumarakhan8647
@anjumarakhan8647 9 ай бұрын
One of the legend of competitive coding Really bro hats off you 🎉❤
@MukeshSharma-xd4dn
@MukeshSharma-xd4dn Жыл бұрын
Superb explanation!!! I was struggling since a long time.
@rohan8758
@rohan8758 10 ай бұрын
@23:11 marJava, MitJava (hindi) words by Aditya Verma.😂😂😂
@abdussamad0348
@abdussamad0348 2 жыл бұрын
solving problem without watching video. Thanks for this awesome series.
@yuggurnani1183
@yuggurnani1183 4 жыл бұрын
Solved it without watching the video....Thank u for such amazing teaching technique @adityaverma please leave a like
@shashankchaturvedi8697
@shashankchaturvedi8697 4 жыл бұрын
can u please share the code
@curtdudeanmol9393
@curtdudeanmol9393 4 жыл бұрын
@@shashankchaturvedi8697 i hope this would be helpful , solved it using java public class LongestSubstringWithKUniqueChars { static Map findUnique(char[] arr, int l, int r){ Map map = new HashMap(); int counter=0; for(int i=l;i k){ while(map.size()>k){ map.put(arr[l], (int)map.get(arr[l])-1); if((int)map.get(arr[l]) == 0){ map.remove(arr[l],map.get(arr[l]) ); } l++; } r++; } } System.out.println(max); } }
@thedataguyfromB
@thedataguyfromB 4 жыл бұрын
@@curtdudeanmol9393 nice code bro
@mayank6023
@mayank6023 3 жыл бұрын
👍👍
@152shivendrakjha4
@152shivendrakjha4 3 жыл бұрын
While True: Print ('Respect❤️')
@opera3846
@opera3846 3 жыл бұрын
IndentationError: ('unindent does not match any outer indentation level')
@imPriyansh77
@imPriyansh77 Жыл бұрын
😂😂😂@@opera3846
@codingwithanonymous890
@codingwithanonymous890 4 жыл бұрын
Sir aap pls graph ka bhi daalna ...
@deepanshuverma6237
@deepanshuverma6237 3 ай бұрын
Correction : Either check == condition after while loop again before incrementing j OR always check == condition at the end of main for loop (less than condition need not to be checked, it will be default flow) Like : public static int lengthOfLongestSubArray(int[] arr, int n, int k) { int j = 0, i = 0, sum = 0; int length = 0; while (j < n) { sum += arr[j]; while (sum > k) sum -= arr[i++]; if (sum == k) length = Math.max(length, j - i + 1); j++; } return length; }
@deepanshuverma6237
@deepanshuverma6237 3 ай бұрын
public int longestkSubstr(String s, int k) { // code here HashMap map = new HashMap(); char[] arr = s.toCharArray(); int i = 0, length = 0; for (int j = 0; j < arr.length; j++) { map.put(arr[j], map.getOrDefault(arr[j], 0) + 1); while (map.size() > k) { if (map.get(arr[i]) == 1) { map.remove(arr[i]); } else { map.put(arr[i], map.get(arr[i]) - 1); } i++; } if (map.size() == k) { length = Math.max(length, j - i + 1); } } return length; }
@somnathnavale9120
@somnathnavale9120 3 жыл бұрын
Why not to use set ? -> let's take string a a b a c b e b e be When j is pointing to e that time set size will be 4 so we will erase the str[i] from set so 'a' will be erased from set . And but after that we will increment the i , now i is pointing to 'a' but in future when set size become greater than K that time we will remving str[i] that 'a' but now 'a' is not present in set so it will point to s.end() we will not able to move forward it is better to use map over set.
@imPriyansh77
@imPriyansh77 Жыл бұрын
Can you re-explain it ? I didn't get it. Please explain why can't we use set & what are the advantages of using map in this particular problem. Thanks
@AnkitGuptaYoutube
@AnkitGuptaYoutube Жыл бұрын
Java Code For Your Reference:- Approach: 1. Keep on building the substring from j=0 [increasing the window size] and log occurance of each character in a Map. 2. If map size (Unique Characters in Map) becomes greater than k, keep on reducing window size (increase i pointer) and decrease the occurrence of characters from Map till map size becomes
@bhupendrakalal1727
@bhupendrakalal1727 3 ай бұрын
best explanation sir , kya hi bolu me ,shabd nhi h mere pass
@sanjeevkumarnirmal5316
@sanjeevkumarnirmal5316 4 жыл бұрын
Sir g , aap hi mere guru hai🙏🙏. Thank u very much for your priceless teaching❤️❤️. Backtracking bhi padha dijiyega jldi se.
@mansisingh6493
@mansisingh6493 2 жыл бұрын
Sir, in the last loop when the condition is greater than k then..after we increase i and remove calculations of i..we would have to calculate the ans first if the condition equals k..after that we would be increasing j..am i right?
@Erawan4466
@Erawan4466 2 жыл бұрын
Yes u r right!
@ankushladani496
@ankushladani496 Жыл бұрын
Explaination was awesome...❤🎉
@dineshkinibailoor340
@dineshkinibailoor340 2 жыл бұрын
In str = "aabacbebebe", first max sub string is "aabacb" not "aabac" at 6:12
@abdussamad0348
@abdussamad0348 2 жыл бұрын
Easy Js approach of a similar question Leetcode problem 3: function lengthOfLongestSubstring(s) { let [start, end, ans] = [0, 0, 0]; let set = new Set(); if (s.length === 0) return ans; while (end < s.length) { if (set.has(s[end])) { while (s[start] !== s[end]) { set.delete(s[start]); start++; } set.delete(s[start]); start++; ans = Math.max(ans, end - start + 1); } else { set.add(s[end]); ans = Math.max(ans, end - start + 1); end++; } } return ans; }
@yoho542
@yoho542 Жыл бұрын
finally solved the problem thank you sir
@ayushyadav4180
@ayushyadav4180 3 жыл бұрын
ye to promotion bhi mast tareeke se karta hai :)
@krishnapandey2542
@krishnapandey2542 2 жыл бұрын
thanku bhaiya thanku so much, after struggling alot now i'm able to solve problem
@llo.welc_me
@llo.welc_me 2 жыл бұрын
Best explanation ever dada love from Kolkata ❤️,keep going dada and keep teaching us like this❤️❤️
@aarishfaiz7880
@aarishfaiz7880 Ай бұрын
Amazing Video Sir You are great.
@laveshgarg2189
@laveshgarg2189 3 жыл бұрын
In the third condition map.size() > k after the while loop whose cond is run wgile loop until map.size()>k when while loop terminate a condition occur map.size() == k which we are not considering and we have to take care of this condition
@g1patil
@g1patil 3 жыл бұрын
I wrote this in MitJava and it worked successfully, Universal algo
@anshuldhanker5383
@anshuldhanker5383 3 жыл бұрын
Java Solution According to this video and runs on gfg class Solution { public int longestkSubstr(String s, int k) { HashMap hm=new HashMap(); int i =0; int j =0; int maxStringlen=-1; while(jk && i
@devanshprakash8354
@devanshprakash8354 2 жыл бұрын
Bro ur code is not working for testcase: s="abcbdbdbbdcdabd" K=5 Pls look into it
@shivamgarg8398
@shivamgarg8398 2 жыл бұрын
class Solution { public int longestkSubstr(String s, int k) { int j =0,i=0,msl=-1; HashMap map=new HashMap(); while(jk && i< s.length()) { // map.merge(s.charAt(i), -1, Integer::sum); if(map.containsKey(s.charAt(i))) { map.put(s.charAt(i), map.get(s.charAt(i))-1); } if(map.get(s.charAt(i)) ==0 ) map.remove(s.charAt(i)); i++; } j++; } } return (msl); } } Runtime error : time limit exceed ... :| can you pls help !!!
@abheykalia3409
@abheykalia3409 2 жыл бұрын
Another slight optimization-> whenever we move i to the next index, we can also increase j because when we get a candidate for a particular window size, increasing i and not j will only reduce the window size, leading to extra work. because the smaller window now will never be the ans to the problem
@_CodeLifeChronicles_
@_CodeLifeChronicles_ 4 ай бұрын
best explanation ever
@satyamshukla7922
@satyamshukla7922 Жыл бұрын
best teacher ever
@RichaSharma-mt4lm
@RichaSharma-mt4lm 2 жыл бұрын
Thanks Aditya, very valuable series 🙌
@RohitPatil_Tech
@RohitPatil_Tech 2 жыл бұрын
Thank you so much! The video was very helpful 🙂
@hello6847
@hello6847 5 ай бұрын
In GFG, just take ans=-1 Because if you didn't find any valid subarray with sum then ans remains -1 but if you take ans = INT_MIN and if you didn't find any valid subarray then it will remains ans INT_MIN and return
@agni5051
@agni5051 2 жыл бұрын
Big fan sir!!!! Autograph milega?
@SuperNirajpandey
@SuperNirajpandey 3 жыл бұрын
@Aditya Verma Respect for you brother :)
@anshikaagrawal9973
@anshikaagrawal9973 2 жыл бұрын
Wao you made this question very easy. Thanks for making all these videos and helping us but just one suggestion. Don't repeat same thing again and again so many times because it might increase the time unnecessarily.
@deependu__
@deependu__ 3 жыл бұрын
bhaiya, you explained very nicely. thank you. but, 0:55 🤣🤣🤣🤣. means data structure aata ho, but loops, conditionals ni.🤣🤣
@less_ordinary
@less_ordinary 3 жыл бұрын
Code in java: class Solution { public int longestkSubstr(String s, int k) { HashMap map=new HashMap(); char ch[]=s.toCharArray(); int i=0,j=0; int max=-1; while(jk) { while(map.size()>k) { if(map.get(ch[i])>0) { map.put(ch[i],map.get(ch[i])-1); if(map.get(ch[i])==0) map.remove(ch[i]); } i++; } j++; } } return max; } }
@oisheedeb481
@oisheedeb481 7 ай бұрын
hii, I also code in java so rather than using HashMap cant we use HashSet for this problem ?
@devanshprajapati4764
@devanshprajapati4764 2 жыл бұрын
why dont we check m.size()==k in else part of m.size()>k...maybe while decrementing i, we can get size ==k again but while next iteration of j ,value gets incresed nd we miss that solution ??
@kaukuntlaprudviraj108
@kaukuntlaprudviraj108 2 жыл бұрын
In my opinion it's good to keep that statement in code but even if u not that doesn't change the answer becoz after removing however it will be having less size compared to previous one
@vaibhavgupta258
@vaibhavgupta258 Жыл бұрын
Thankyou So much 😍 Very simple & Unique Explanation Guyz C++ Code Solution:(Jisko Help leni hai yha se le sakta hai) class Solution{ public: int longestKSubstr(string str, int k) { int i = 0, j = 0; unordered_map mp; int maxi = INT_MIN; while(j < str.length()) { mp[str[j]]++; if(mp.size() < k) { j++; } else if(mp.size() == k) { maxi = max(maxi, j - i + 1); j++; } else if(mp.size() > k) { while(mp.size() > k) { mp[str[i]]--; if(mp[str[i]] == 0) mp.erase(str[i]); i++; } j++; } } return maxi; } };
@shubhamkumarmandal2132
@shubhamkumarmandal2132 Жыл бұрын
Have you solve the problem, longest substring with atleast k repeating character
@imPriyansh77
@imPriyansh77 Жыл бұрын
Can you explain why using set was not adviced by Aditya Sir in the video ?
@Bnishma
@Bnishma 3 жыл бұрын
Thanks @Aditya Verma Java solution: public int longestkSubstr(String s, int k) { Map map=new HashMap(); int j=0; int i=0; int max=-1; while (j < s.length()) { map.put(s.charAt(j), map.getOrDefault(s.charAt(j), 0) + 1); if (map.size() == k) { max = Math.max(max, j - i + 1); } else if (map.size() > k) { while (map.size() > k) { map.put(s.charAt(i), map.get(s.charAt(i)) - 1); if (map.get(s.charAt(i)) == 0) map.remove(s.charAt(i)); i++; } } j++; } return max; }
@sakshi6252
@sakshi6252 2 жыл бұрын
@Aditya Verma Sir, please make video on Binary Tree and backtracking
@ayushk4142
@ayushk4142 2 жыл бұрын
one query: at 20:00 when we hit "cbe" this is also a potential candidate but we are not considering it why ? as per this question I guess it does not matter, but what if the question ask to find the smallest substring with K unique characters
@your_name96
@your_name96 2 жыл бұрын
won't replacing max by min work ?
@ahmednafis
@ahmednafis 2 жыл бұрын
in that case u have to check after the nested while loop too
@AbhishekYadav-rm4hw
@AbhishekYadav-rm4hw Жыл бұрын
We can store the count of unique characters in a variable and don't have to delete the entry from the map everytime count becomes zero. Below is the same C++ program: int longestKSubstr(string s, int k) { int i=0, j=0; int n = s.length(); map mp; int count = 0; int ans = -1; while(j
@noober7397
@noober7397 Жыл бұрын
OR we can skip the "count" variable altogether and decrement K whenever we encounter a distinct character. So whenever we have K < 0, we know that we have more distinct characters than required. int longestKSubstr(string s, int k) { int i = 0, j = 0, ans = -1; unordered_map m; for(j = 0; j < s.size(); j++){ if(!m[s[j]]++) k--; while(k < 0) if(--m[s[i++]] == 0) k++; if(k == 0) ans = max(ans,j-i+1); } return ans; }
@AbhishekYadav-rm4hw
@AbhishekYadav-rm4hw Жыл бұрын
@@noober7397 I don't mind creating one more variable as it doesn't impact the TC or SC .. just my opinion
@sarveshjoshi6913
@sarveshjoshi6913 6 ай бұрын
are bhai yha pe jab cndn< k hoga tab bhi maxi = max(maxi,j-i+1) krna padega na
@vakhariyajay2224
@vakhariyajay2224 Жыл бұрын
Thank you very much. You are a genius.
@sankalparora9374
@sankalparora9374 Жыл бұрын
The explanation cannot be better.
@chandrachurmukherjeejucse5816
@chandrachurmukherjeejucse5816 Жыл бұрын
Great lectures sir.
@kshitizsinghchauhan7464
@kshitizsinghchauhan7464 2 жыл бұрын
Java, marjava, mitjava🤣🤣Op BTW really good explanation!
@jaypratap3888
@jaypratap3888 Жыл бұрын
In the last condition when unique characters are more than k , Do we need to have a check of the unique characters after doing i++, I think I we have to Please correct me If I am wrong ,Providing the code snippet for reference. while(j < s.length() ){ uc[s[j]]++; if(uc.size() == k) ans = max(ans, j-i+1); else{ while(uc.size() > k ){ uc[s[i]]--; if(uc[s[i]] == 0) uc.erase(s[i]); i++; if(uc.size() == k) ans = max(ans, j-i+1); } } j++; }
@utpalpodder6431
@utpalpodder6431 4 жыл бұрын
Can you start the backtracking playlist too. ..it will be helpful. .
@divyagarg3283
@divyagarg3283 3 жыл бұрын
@Aditya Verma how can we solve it for case of atleast or atmost???
@sanchitbatra4431
@sanchitbatra4431 3 жыл бұрын
On 20.25 , before moving j forward , dont we need to check if that cbe was the possible candidate or not?? How are you checking that?
@SAURABHSINGH-xp8dm
@SAURABHSINGH-xp8dm 3 жыл бұрын
Yes we have to do it
@imPriyansh77
@imPriyansh77 Жыл бұрын
we need to check it
@rohitsingh-te3iv
@rohitsingh-te3iv 2 жыл бұрын
javascript code function longestSubstring(arr , k){ let i=0; let j=0; // assume there is no max at initial let max = -1; let hMap = new Map(); // iterate over the window while(j
@mohitswain8441
@mohitswain8441 4 жыл бұрын
Last else if condn. Mai hum while loop ke baad abar mp.size() == k ho jayega to use check nahi karenge?
@anjana1700
@anjana1700 4 жыл бұрын
I too had the same doubt because j++ is also done then what if next character increases the map size then one case will be lost
@sudeepchowdhary2577
@sudeepchowdhary2577 4 жыл бұрын
In the last while loop we are removing some elements from the window, therefore the size of window will definitely reduce from the current size and we've already taken care of the largest valid window size up to this position (in 2nd condition). So, even if mp.size() becomes equal to K in the last else if, then the window size will either be equal to or smaller than the current largest but not greater. Hence no need to check again.
@ManojKumar-yt8qd
@ManojKumar-yt8qd 4 жыл бұрын
@@sudeepchowdhary2577 thank u dude. That j++ was haunting me alot.
@ritikagupta8847
@ritikagupta8847 3 жыл бұрын
@@sudeepchowdhary2577 Yes you are right but in case of previous question we cannot do j++ in sum>k case. eg: ar=[1,1,1,1,4] and k=5 . Here we will go from k and miss [1,4] window.
@sunnykakrani7830
@sunnykakrani7830 3 жыл бұрын
@@sudeepchowdhary2577 if we have to print all substrings with k unique characters in that case we are lacking from the substring "cbe"
@NamanSondhi-t3k
@NamanSondhi-t3k Жыл бұрын
When will your videos come on other patterns like pattern Two pointer, pattern Fast slow pointer, pattern cyclic sort and other patterns. I can only see videos of pattern sliding window. :( Eagerly waiting for other pattern videos. Love your way of explanation. :)
@sameersahu4569
@sameersahu4569 3 жыл бұрын
I have a doubt when the size of map is greater than k to after reducing the map size if the value become equal to k unique characters....in that case we have to check for maxlength there also right?
@mohitmotwani9256
@mohitmotwani9256 3 жыл бұрын
when size of map is greater than k, we go into the while loop and we come out of the while loop only when the size of the map(no. of unique characters) is k, so we check for the maxLength in this case only.
@laveshgarg2189
@laveshgarg2189 3 жыл бұрын
@Sameer Sahu ya bro we have to check this consition
@Kaivalyamani
@Kaivalyamani 3 жыл бұрын
If k=4 then we got some length n and when mapsize is greater than k so if we decrease then either length of another candidate will be n or less than n. So no need to check
@penumono
@penumono Жыл бұрын
My javascript solution using hashmap and sliding window let longestSubString = (s, k)=> { let [i, j, len, count, obj] = [0, 0, -1, 0, {}]; while(j < s.length) { let char = s.charAt(j); if(!(char in obj)) count++; obj[char] = obj[char]+1||1; if(count < k) j++; else if(count === k) { len = Math.max(len, j-i+1); j++; } else { while(count > k) { // removal of i let word = s.charAt(i); obj[word]-=1; if(obj[word] === 0) { delete obj[word]; count--; } i++; len = Math.max(len, j-i+1); } j++; } } return len } console.log(longestSubString("aabacbebebe", 3))
@nirajgujarathi6796
@nirajgujarathi6796 3 жыл бұрын
great teaching skills !
@M11-z5e
@M11-z5e 2 жыл бұрын
Solution in Python :: def longest_sub(arr,k): i,j = 0,0 n = len(arr) dicty = {} max_sub = 0 while(jk): if arr[i] in dicty.keys(): dicty[arr[i]] -= 1 if dicty[arr[i]] == 0: del dicty[arr[i]] i+=1 j+=1 if max_sub==0: return -1 else: return max_sub a =list("abcabcabcabcabcabcaba") k = 2 print(longest_sub(a,k))
@corhymer1626
@corhymer1626 7 ай бұрын
Amazing video
@Augustin_17-i2k
@Augustin_17-i2k 11 ай бұрын
thank you bhaiya for your efforts........... by seeing the problem stmt i solved the problem
@shikharbijpuria3387
@shikharbijpuria3387 4 жыл бұрын
What is the sequence for learning data structure? which data structure we have to learn first and which on second
@ManojKumar-yt8qd
@ManojKumar-yt8qd 4 жыл бұрын
first of all learn basic DS like array, linked list, stack, queue and then you can start exploring containers in STL. I am providing a link for STL : kzbin.info/www/bejne/sHPLh42wnpqFmrc. thank me later😎
@rishabsharma5307
@rishabsharma5307 3 жыл бұрын
// Longest substring with K unique characters int longestSubstringWithKUniqueCharacters(string str, int n, int k) { int i, j, res = INT_MIN; map mp; i = j = 0; while(j < n) { mp[str[j]]++; if(mp.size() == k) res = max(res, j-i+1); else if(mp.size() > k) { while(mp.size() > k) { mp[str[i]]--; if(mp[str[i]] == 0) mp.erase(str[i]); ++i; if(mp.size() == k) res = max(res, j-i+1); } } ++j; } return res; }
@josephaj8310
@josephaj8310 2 жыл бұрын
Should we need to check for mpp.size() == k in mpp.size() > k block as we may miss some potential answer after deleting i in the map??
@vitaminprotein2217
@vitaminprotein2217 2 жыл бұрын
yes we should
@theDarkRanger00
@theDarkRanger00 Жыл бұрын
class Solution{ public: int longestKSubstr(string s, int k) { int n=s.length(); int i=0; int j=0; int count=0; unordered_map mp; mp.clear(); int res=0; while(jk){ // reduce the frequency of the leftmost window character mp[s[i]]--; //if the frequency is 0 it does not exist in the window so we remove it from the map and reduce the unique element count if(mp[s[i]]==0){ mp.erase(s[i]); count--; } i++; //if it hits the condition while removing unique elements then we update the result if(count==k){ res=max(res,j-i+1); } } j++; } } return res==0? -1: res; } }; Did it without seeing the video , thanks to the previous video, any suggestions in the code will be appreciated
@theDarkRanger00
@theDarkRanger00 Жыл бұрын
Just realized from a solutions and comments below that could have simply used map.size() instead of keeping that count, or could have kept the count instead of erasing
@nayanjha5670
@nayanjha5670 Жыл бұрын
bhaiya your description made my day- my girlfriend 🤣🤣🤣 by going to link mai haste haste gir gya 🤣😅
@googleit2490
@googleit2490 Жыл бұрын
Understood :) Solved before watching video using set and map, changed to only map after watching the video... Sep'27, 2023 04:11 pm
@imPriyansh77
@imPriyansh77 Жыл бұрын
Can you explain why using set was not adviced by Aditya Sir in the video ?
@Codekage1
@Codekage1 2 жыл бұрын
Almost Solved the question without video i was just making mistake in while condition where i was not incrementing j
Cat mode and a glass of water #family #humor #fun
00:22
Kotiki_Z
Рет қаралды 42 МЛН
How Strong Is Tape?
00:24
Stokes Twins
Рет қаралды 96 МЛН
Minimum Window Substring | Variable Size Sliding Window
40:35
Aditya Verma
Рет қаралды 205 М.
Count Occurrences Of Anagrams | Sliding Window
39:56
Aditya Verma
Рет қаралды 236 М.
Why You Shouldn't Nest Your Code
8:30
CodeAesthetic
Рет қаралды 2,8 МЛН
one year of studying (it was a mistake)
12:51
Jeffrey Codes
Рет қаралды 108 М.
why are switch statements so HECKIN fast?
11:03
Low Level
Рет қаралды 437 М.
Starting Competitive Programming - Steps and Mistakes
9:55
William Lin (tmwilliamlin168)
Рет қаралды 1,4 МЛН
Naming Things in Code
7:25
CodeAesthetic
Рет қаралды 2,3 МЛН
This Algorithm is 1,606,240% FASTER
13:31
ThePrimeagen
Рет қаралды 860 М.
Cat mode and a glass of water #family #humor #fun
00:22
Kotiki_Z
Рет қаралды 42 МЛН