Тёмный

Longest Substring With K Unique Characters | Variable Size Sliding Window 

Aditya Verma
Подписаться 251 тыс.
Просмотров 160 тыс.
50% 1

Become a Competitive Programming Hero with this structured batch to help all levels of programmers sharpen their skills: unacademy.cc/AVBAT
[FREE] Beginners lessons in programming by Codechef: unacademy.com/...
Patreon Link: / adityaverma
Video Pdf Notes And Code: / 45213007
Playlist Link: • Sliding Window Algorit...
Problem Description: practice.geeks...
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 .
------------------------------------------------------------------------------------------
Here are some of the gears that I use almost everyday:
🖊️ : My Pen (Used in videos too): amzn.to/38fKSM1
👨🏻‍💻 : My Apple Macbook pro: amzn.to/3w8iZh6
💻 : My gaming laptop: amzn.to/3yjcn23
📱 : My Ipad: amzn.to/39yEMGS
✏️ : My Apple Pencil: amzn.to/3kMnKYf
🎧 : My Headphones: amzn.to/3kMOzM7
💺 : My Chair: amzn.to/385weqR
🛋 : My Table: amzn.to/3kMohtd
⏰ : My Clock: amzn.to/3slFUV3
🙋🏻‍♀️ : My girlfriend: amzn.to/3M6zLDK ¯\_(ツ)_/¯
PS: While having good gears help you perform efficiently, don’t get under the impression that they will make you successful without any hard work.

Опубликовано:

 

30 сен 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 397   
@MiraclePlayzzzz
@MiraclePlayzzzz 3 года назад
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 2 года назад
Moon-policy kahte hai shayad
@gunjakumari1951
@gunjakumari1951 2 года назад
Yep
@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
@_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!
@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 11 месяцев назад
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 }
@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 3 месяца назад
same here :D
@akashpurbia4390
@akashpurbia4390 7 месяцев назад
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
@349_rahulbhattacharya6
@349_rahulbhattacharya6 2 года назад
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 Год назад
@@kartiksrivastava3897 same question
@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
@priyanshkumar17
@priyanshkumar17 11 месяцев назад
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
@codingwithanonymous890
@codingwithanonymous890 3 года назад
Sir aap pls graph ka bhi daalna ...
@rohan8758
@rohan8758 7 месяцев назад
*Vote for Trees series by Aditya Verma!!!!*
@ShivanshSingh-q2d
@ShivanshSingh-q2d 20 дней назад
GFG simple solution c++ int longestKSubstr(string s, int k) { int n = s.length(); int i = 0, j = 0, maxlen = -1; map mp; while (j < n) { mp[s[j]]++; // If the number of unique characters is less than k, move the right pointer if (mp.size() < k) { j++; } // If the number of unique characters is exactly k, update the maximum length else if (mp.size() == k) { maxlen = max(maxlen, j - i + 1); j++; } // If unique characters exceed k, move the left pointer else { while (mp.size() > k) { mp[s[i]]--; if (mp[s[i]] == 0) { mp.erase(s[i]); } i++; } j++; } } // If the number of unique characters in the string is less than k, return -1 if (mp.size() < k) { return -1; } return maxlen; }
@penumono
@penumono 10 месяцев назад
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))
@kanakmittal3756
@kanakmittal3756 2 года назад
Was able to solve this problem without even watching the video. Thank You so much.
@rohan8758
@rohan8758 7 месяцев назад
@23:11 marJava, MitJava (hindi) words by Aditya Verma.😂😂😂
@152shivendrakjha4
@152shivendrakjha4 3 года назад
While True: Print ('Respect❤️')
@opera3846
@opera3846 3 года назад
IndentationError: ('unindent does not match any outer indentation level')
@priyanshkumar17
@priyanshkumar17 11 месяцев назад
😂😂😂@@opera3846
@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; }
@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
@ashrafsir69
@ashrafsir69 11 месяцев назад
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.
@priyanshkumar17
@priyanshkumar17 11 месяцев назад
Same here ! Thanks
@shalinidwivedi7827
@shalinidwivedi7827 3 года назад
Marjava mitjava 😂
@TuringTested01
@TuringTested01 Год назад
itna funny bhi nahi tha ki aankho se paani aarha h
@RonitTomar-tq7zy
@RonitTomar-tq7zy 7 месяцев назад
import java.util.*; public class LongestSubStrWithKUniqueChar { public static int uniqueChar(String s) { int n = s.length(); int k = 1; int ans = 0; int max1 = -1; LinkedHashMap map = new LinkedHashMap(); int i=0; int j=0; while(j>>>>>>>
@tekbssync5727
@tekbssync5727 3 года назад
starting 5s and ending 5s. Booster sound fills me with 200% energy 🧡😁
@anshulpandey6576
@anshulpandey6576 3 года назад
absolutely true.......
@mansisingh6493
@mansisingh6493 Год назад
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 Год назад
Yes u r right!
@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
@priyanshkumar17
@priyanshkumar17 11 месяцев назад
correct, thanks
@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
@ayushyadav4180
@ayushyadav4180 3 года назад
ye to promotion bhi mast tareeke se karta hai :)
@Codekage1
@Codekage1 Год назад
Almost Solved the question without video i was just making mistake in while condition where i was not incrementing j
@anshuldhanker5383
@anshuldhanker5383 2 года назад
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 !!!
@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
@vipulgupta3915
@vipulgupta3915 3 года назад
Working Code: public static void findMaxStringWithKChar(String str,int k) { int i=0,j=0; HashMap map = new HashMap(); int maxLength = 0; while(jk) { map.put(str.charAt(i), map.get(str.charAt(i))-1); if(map.get(str.charAt(i))==0) map.remove(str.charAt(i)); i++; } j++; } } System.out.println(maxLength); }
@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 Месяц назад
is this code accepting all testcases, i tried it doesn't?
@magha786
@magha786 Год назад
Java , marjava , mitjava 😂😂😂😂
@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
@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.
@priyanshkumar17
@priyanshkumar17 11 месяцев назад
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
@shashankpandey6111
@shashankpandey6111 Год назад
I was trying to solve this question with set, but getting answer as 5, can anyone tell me what is wrong in this code. private void findLongestSubString(String str, int k) { int i = 0, j = 0, count = 0, left = 0, maxLength = 0; Set set = new HashSet(); while (j < str.length()) { if (set.contains(str.charAt(j))) { left++; j++; } else { set.add(str.charAt(j)); count++; j++; } if (count < k) { j++; } else if (count == k) { maxLength = Math.max(maxLength, count + left); j++; } else if (count > k) { while (count > k) { if (set.contains(str.charAt(i))) { set.remove(str.charAt(i)); count--; i++; } else { left--; i++; } } if (count == k) maxLength = Math.max(maxLength, count + left); j++; } } System.out.println(maxLength); }
@anonymouscode31
@anonymouscode31 3 года назад
why good teaching RU-vidrs ruin their content by getting sold by some shit company?
@PawanKumar-hq6dy
@PawanKumar-hq6dy 3 дня назад
//longest substring with unique k characters /* * input String str = "abbbcdbcf", k =3 * output = ceeeeeeeef =10 * //hashmap = count of each , if total length of hashmap = 3 , mark it as unque..increment i * */ public int longestSubstringWithUnquie(String str, int k){ int i=0,j=0, maxLength =0; Map map = new HashMap(); while (jk){ while (map.size()>k){ map.put(str.charAt(i) , map.get(str.charAt(i))-1); if(map.get(str.charAt(i)) ==0){ map.remove(str.charAt(i)); } i++; } } if(map.size() == k){ if((j-i+1)>maxLength){ maxLength = j-i+1; } map.put(str.charAt(i) , map.get(str.charAt(i))-1); if(map.get(str.charAt(i)) ==0){ map.remove(str.charAt(i)); } i++; } j++; } return maxLength; }
@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 4 месяца назад
hii, I also code in java so rather than using HashMap cant we use HashSet for this problem ?
@hello6847
@hello6847 Месяц назад
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
@AnkitGuptaYoutube
@AnkitGuptaYoutube 9 месяцев назад
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
@vaibhavsahay1323
@vaibhavsahay1323 2 месяца назад
code in java : import java.util.HashMap; public class LongestSubstringWithoutRepeating { public int lengthOfLongestSubstringKDistinct(String s, int k) { if (s == null || s.length() == 0 || k == 0) return 0; HashMap map = new HashMap(); int left = 0, right = 0, maxLength = 0; while (right < s.length()) { char currentChar = s.charAt(right); map.put(currentChar, map.getOrDefault(currentChar, 0) + 1); while (map.size() > k) { char leftChar = s.charAt(left); map.put(leftChar, map.get(leftChar) - 1); if (map.get(leftChar) == 0) { map.remove(leftChar); } left++; } maxLength = Math.max(maxLength, right - left + 1); right++; } return maxLength; } public static void main(String[] args) { LongestSubstringWithoutRepeating solution = new LongestSubstringWithoutRepeating(); String s = "eceba"; int k = 2; System.out.println(solution.lengthOfLongestSubstringKDistinct(s, k)); } }
@shlokhinge3179
@shlokhinge3179 3 года назад
Legend is back🔥 Btw ,Your old into music was fab ..!! Plz Continue with it🙏😁
@sonianarendramodi2605
@sonianarendramodi2605 2 года назад
@@ujjawal.pandey lol
@corhymer1626
@corhymer1626 3 месяца назад
Amazing video
@nayanjha5670
@nayanjha5670 Год назад
bhaiya your description made my day- my girlfriend 🤣🤣🤣 by going to link mai haste haste gir gya 🤣😅
@deepakkumarsharma-cp7kv
@deepakkumarsharma-cp7kv 6 месяцев назад
coding implementation of above explanation private static int longestkSubstr(String s, int k) { int i = 0, j = 0; int n = s.length(); int ans = 0; Map map = new HashMap(); while (j < n) { map.put(s.charAt(j), map.getOrDefault(s.charAt(j), 0) + 1); if (map.size() < k) { j++; } else if (map.size() == k) { ans = Math.max(ans, j - i + 1); j++; } else { 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 ans; }
@abrahamlincoln5724
@abrahamlincoln5724 Год назад
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 Год назад
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
@ਹੈਪ੍ਪੀਕੰਬੋਜ
JAVA code:- import java.util.*; public class longest_substring_unique_chara { public static void main(String[] args) { String str = "aabacbebebe"; int k = 3, i = 0, j = 0, subsize = 0; HashMap map = new HashMap(); while (j < str.length()) { map.put(str.charAt(j), map.getOrDefault(str.charAt(j), 0) + 1); if (map.size() < k) { j++; } else if (map.size() == k) { subsize = Math.max(subsize, j - i + 1); j++; } else if (map.size() > k) { while (map.size() > k) { int dec = map.get(str.charAt(i)); int decvalue = dec - 1; map.put(str.charAt(i), decvalue); if (decvalue == 0) map.remove(str.charAt(i)); i++; } subsize = Math.max(subsize, j - i + 1); j++; } } System.out.println(subsize); } }
@divyagarg3283
@divyagarg3283 3 года назад
@Aditya Verma how can we solve it for case of atleast or atmost???
@tusharsrivastava3338
@tusharsrivastava3338 Год назад
For C++, we can use a vector instead of a map; 0th index of the vector will keep the count of 'a' and 26th will store the count of 'z'. Suppose we have characters 'a' and 'b' in our window. then the vector will have 24 zeroes; vector = {1,1,0,0,0,0....,0,0}. Then for each iteration will calculate 26-(count of zeroes in the vector) compare that to K. Code below: int longestKSubstr(string s, int k) { vector cnt(26,0); int ans = 0, i = 0, j = 0; while(j
@nageshwarmali9631
@nageshwarmali9631 Год назад
wow brother
@b_01_aditidonode43
@b_01_aditidonode43 8 месяцев назад
thanks sir, you explained the variable sliding format so well that I was able to solve the question on my own..
@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()
@varunpalsingh3822
@varunpalsingh3822 7 месяцев назад
if anybody uses python, then use defaultdict(int) instead of normal hashmap, as you will not be able to get size of normal hashmap
@mohitswain8441
@mohitswain8441 3 года назад
Last else if condn. Mai hum while loop ke baad abar mp.size() == k ho jayega to use check nahi karenge?
@anjana1700
@anjana1700 3 года назад
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 3 года назад
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 3 года назад
@@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"
@M11-z5e
@M11-z5e Год назад
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))
@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
@sakshi6252
@sakshi6252 2 года назад
@Aditya Verma Sir, please make video on Binary Tree and backtracking
@shekharsingh5204
@shekharsingh5204 3 месяца назад
```#include using namespace std; int longestKSubstr(string s, int k) { unordered_map mp; int i = 0, j = 0; int mx = -1; int count = 0; int n = s.size(); while (j < n) { if (mp.find(s[j]) == mp.end() || mp.find(s[j]) != mp.end() && mp[s[j]] == 0) count++; mp[s[j]]++; if (count < k) j++; else if (count == k) { mx = max(mx, j - i + 1); j++; } else if (count > k) { while (count > k) { if (mp[s[i]] > 0) { mp[s[i]]--; } if (mp[s[i]] == 0) count--; i++; } if (count == k) mx = max(mx, j - i + 1); j++; } } return mx; } int main(){ cout
@immrhrr
@immrhrr 4 месяца назад
int longestKSubstr(string s, int k) { int n = s.size(); int i = 0, j = 0; int cnt = -1; // Initialize to -1 to handle the case where no valid substring is found map mp; while (j < n) { mp[s[j]]++; if (mp.size() < k) { // Do nothing specific here since j is incremented at the end of the loop } else if (mp.size() == k) { // Update the maximum length found cnt = max(cnt, j - i + 1); } else { // When there are more than k unique characters, move the start of the window while (mp.size() > k) { mp[s[i]]--; if (mp[s[i]] == 0) { mp.erase(s[i]); } i++; } // We do not need to increment j here because it will be incremented at the end of the loop } j++; // Increment j at the end of the loop to move the window's end forward } return cnt; }
@kshitizsinghchauhan7464
@kshitizsinghchauhan7464 2 года назад
Java, marjava, mitjava🤣🤣Op BTW really good explanation!
@deepanshuverma6237
@deepanshuverma6237 9 дней назад
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 9 дней назад
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; }
@Hemanthkumar-ck1zu
@Hemanthkumar-ck1zu 3 месяца назад
int longestUniqueSubsttr(string s){ //code int i =0 , j=0 ; int A[26]={0}; int maxi =INT_MIN; while(j1) { A[s[i]-'a']--; i++; } maxi=max(maxi , j-i+1); j++; } return maxi ; }
@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
@biswarupacharjya2258
@biswarupacharjya2258 8 месяцев назад
int i=0,j=0; int maxi=INT_MIN; int count=0; unordered_map map; while(jk){ map[str[i]]--; if(map[str[i]]==0){ map.erase(str[i]); } i++; } j++; } } return maxi;
@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
@sharad8817
@sharad8817 3 месяца назад
please anybody tell me general format works everytime ??
@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
@priyanshkumar17
@priyanshkumar17 11 месяцев назад
we need to check it
@SaurabhMishraa
@SaurabhMishraa 11 месяцев назад
Java-------->>Understandable code class Solution { public int longestkSubstr(String s, int k) { int i = 0; int j = 0; int n = s.length(); int max = -1; if (s == null || s.length() == 0 || k 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; } }
@sanjeevkumar-iw2lz
@sanjeevkumar-iw2lz 2 года назад
// my implementation int findLength(string str, int k) { int n = str.length(); unordered_map mp; int maxSize = 0; int i = 0; int j = 0; while(i k) { mp[str[i]]--; if(mp[str[i]] == 0) // if that elenent is no more then we have to erase it, either it will continue with value in negative and result in segmentaiton fault mp.erase(str[i]); i++; if(mp.size() == k) { int count = 0; for(auto it = mp.begin(); it != mp.end(); it++) count = count + it->second; maxSize = max(maxSize, count); } } j++; } } return maxSize; } // if any mistake is there please message me.
@siddojugouthamnitap8801
@siddojugouthamnitap8801 7 месяцев назад
static int longestkSubstr(String s, int k) { HashMapmap = new HashMap(); int i = 0; int j = 0; int max = -1; while(jk){ while(map.size() != k){ if(map.get(s.charAt(i)) > 1){ map.put(s.charAt(i),map.get(s.charAt(i))-1); } else map.remove(s.charAt(i)); i++; } j++; } } return max; }
@pprathameshmore
@pprathameshmore 2 года назад
You are one of the best teacher ever met for understanding these interview questions!
@RitikRaj-fg7sh
@RitikRaj-fg7sh 7 месяцев назад
int n = s.size(); int st = 0, ed = 0, ans = -1; map mp; while (ed < n) { mp[s[ed]]++; if (mp.size() < k) { ed++; } else if (mp.size() == k) { ans = max(ans, (ed - st + 1)); ed++; } else if(mp.size()>k) { while (mp.size() > k) { mp[s[st]]--; if (mp[s[st]] == 0) mp.erase(s[st]); st++; } ed++; } } return ans ;
@bhupendrakalal1727
@bhupendrakalal1727 15 дней назад
best explanation sir , kya hi bolu me ,shabd nhi h mere pass
@prithvigupta8215
@prithvigupta8215 2 года назад
Why is this not working????? class Solution{ public: int longestKSubstr(string s, int k) { int i=0; int j=0; int n=s.length(); mapm; int mx=-1; while(jk){ m[s[i]]--; if(m[s[i]]==0) { m.erase(s[i]); } i++; } j++; } } return mx; }
@prithvigupta8215
@prithvigupta8215 2 года назад
i put m[s[j]]++ in the beginning of while loop..now its working.
@__ankush_kushwaha
@__ankush_kushwaha 6 месяцев назад
class Solution { public: int longestKSubstr(string s, int k) { int n = s.size(); unordered_map mp; int j = 0; int i = 0; int _max = -1 ; while (j < n) { mp[s[j]]++; if (mp.size() == k) { _max = max(_max, j - i + 1); } if (mp.size() > k) { while (mp.size() > k) { mp[s[i]]--; if (mp[s[i]] == 0) { mp.erase(s[i]); } i++; } } j++; } return _max; } };
@the__developer
@the__developer 10 месяцев назад
class Solution { public: int longestKSubstr(string s, int k) { // Your code goes here int n = s.size(); int i = 0; int j = 0; int maxi = -1; map mp; while (j < n) { mp[s[j]]++; while (mp.size() >k) { mp[s[i]]--; if(mp[s[i]]==0){ mp.erase(s[i]); } i++; } if(mp.size()==k){ maxi=max(maxi,j-i+1); } j++; } return maxi; } };
@krishnapandey2542
@krishnapandey2542 Год назад
int longestKSubstr(string s, int k) { // your code here unordered_map m; int i=0,j=0; int len = -1; while(j < s.size()) { m[s[j]]++; if(m.size() < k) { j++; } else if(m.size() == k) { len = max(len,j-i+1); j++; } else { while(m.size() > k) { if(m[s[i]] == 1) m.erase(s[i]); else m[s[i]]--; i++; } j++; } } return len; } thats how I code it by my self
@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
@pratishdewangan132
@pratishdewangan132 7 месяцев назад
5min into the video and i solved whole question by myself
@dineshkinibailoor340
@dineshkinibailoor340 2 года назад
In str = "aabacbebebe", first max sub string is "aabacb" not "aabac" at 6:12
@sarveshjoshi6913
@sarveshjoshi6913 3 месяца назад
are bhai yha pe jab cndn< k hoga tab bhi maxi = max(maxi,j-i+1) krna padega na
@utpalpodder6431
@utpalpodder6431 3 года назад
Can you start the backtracking playlist too. ..it will be helpful. .
@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
@ganeshkosimala8031
@ganeshkosimala8031 Год назад
2 mins into the video coded it myself .Awesome explanation sir
@ayushsharma8950
@ayushsharma8950 3 года назад
Bro code not working on java
@amansaxena4446
@amansaxena4446 Год назад
agar me ye video dekhra hu to matlab language to aati hogi wrna koi yha tk kese pauch jaega sirji
@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
@priyanshkumar17
@priyanshkumar17 11 месяцев назад
Can you explain why using set was not adviced by Aditya Sir in the video ?
@NotNotNithin
@NotNotNithin 3 года назад
Java solution: public static int findLength(String str, int k) { if(str == null || str.length() == 0 || str.length() < k) { throw new IllegalArgumentException(); } int windowStart = 0, maxLength = 0; Map charFrequencyMap = new HashMap(); // in this for loop, we look to extend the range [windowStart, windowEnd] for(int windowEnd = 0; windowEnd < str.length(); windowEnd++) { char rightChar = str.charAt(windowEnd); charFrequencyMap.put(rightChar, charFrequencyMap.getOrDefault(rightChar, 0) + 1); // shrinking the sliding window until we are left with 'k' distinct characters in the frequency map. while(charFrequencyMap.size() > k) { char leftChar = str.charAt(windowStart); charFrequencyMap.put(leftChar, charFrequencyMap.get(leftChar) - 1); // remove from the frequency map if the number of occurrences become '0' if(charFrequencyMap.get(leftChar) == 0) { charFrequencyMap.remove(leftChar); } windowStart++; // shrinks the window } maxLength = Math.max(maxLength, windowEnd - windowStart + 1); // remember the maxLength so far } return maxLength; } Another Java solution: public static int findLongestSubstringEfficientSolution(String s, int k) { if (s == null || s.length() == 0 || s.length() < k) { throw new IllegalArgumentException(); } Map frequencyMap = new HashMap(); int windowStart = 0, windowEnd = 0, maxLength = Integer.MIN_VALUE; while (windowEnd < s.length()) { // do calculations char rightChar = s.charAt(windowEnd); frequencyMap.put(rightChar, frequencyMap.getOrDefault(rightChar, 0) + 1); if (frequencyMap.size() < k) { windowEnd++; } else if (frequencyMap.size() == k) { // we calculate the window size and update any previous window length maxLength = Math.max(maxLength, (windowEnd - windowStart + 1)); windowEnd++; } else { // Window size is greater than k, so we need to loop to decrement from the left while (frequencyMap.size() > k) { char leftChar = s.charAt(windowStart); frequencyMap.put(leftChar, frequencyMap.get(leftChar) - 1); if (frequencyMap.get(leftChar) == 0) { frequencyMap.remove(leftChar); } windowStart++; } } } return maxLength; }
@tech_wizard9315
@tech_wizard9315 3 года назад
Please make a roadmap to crack google in 6months for DSA beginner, need it in pandemic times!
@AshutoshKumar-mv5um
@AshutoshKumar-mv5um 3 года назад
usse khud to crack krne de
@akashparihar515
@akashparihar515 3 года назад
@@AshutoshKumar-mv5um Bhai Bhai 🤣🤣
@SuperNirajpandey
@SuperNirajpandey 3 года назад
@@AshutoshKumar-mv5um bhai...thora sa respect de dete aditya ko to sahi rehta....just saying
@letscode8697
@letscode8697 2 года назад
so ja bro nai hone vala consistency chahiye aur hardwork 6 month me amazon crack hogi google k liye bauhut mehant chahiye advance leevel problem solving skill chahiye
@amrithapatil4595
@amrithapatil4595 3 года назад
What is the time complexity of this code?
@SunilSharma-mb2kf
@SunilSharma-mb2kf 3 года назад
O(N)
@amrithapatil4595
@amrithapatil4595 3 года назад
@@SunilSharma-mb2kf there is inner while loop to remove chars inside of the outer while loop. So why does that still count O(N)
@manavshah7450
@manavshah7450 3 года назад
the complexity will still be O(N) , in the last while loop that while(condition >k ) the i pointer will only visit the array items only once i.e in the worst case the complexity of this question will be - O(N) due to j travel +O(N) due to i travel
@udaytewary3809
@udaytewary3809 3 месяца назад
But how we are erasing entry from the map which is not a constant operation it takes log(n) so how does the complexity is O(N)
@noneedtoknowthishandle
@noneedtoknowthishandle 7 месяцев назад
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.
@_CodeLifeChronicles_
@_CodeLifeChronicles_ Месяц назад
best explanation ever
@RohitPatil_Tech
@RohitPatil_Tech 2 года назад
Thank you so much! The video was very helpful 🙂
@Bzgwk
@Bzgwk Год назад
if anyone is looking for the JAVA solution public static void main(String[] args) { String str= "aabacbebebe"; int k=3; int i=0,j=0; int maxSize= Integer.MIN_VALUE; HashMap map= new HashMap(); while(jk) { int val= map.get(str.charAt(i)); val--; if(val==0) { map.remove(str.charAt(i)); } else { map.put(str.charAt(i), val); // val is decreased and the added to map } i++; } j++; } } System.out.println(maxSize); }
@mohit84604
@mohit84604 Год назад
JAVASCRIPT SOLUTION :- let string = "aabacbebebe" function solve(string,k) { let i = 0; let j = 0; let map = new Map() let max = 0; while (j < string.length) { if(map.get(string[j]) >= 0){ map.set(string[j],map.get(string[j]) + 1) }else{ map.set(string[j],0) } if(map.size < k){ j++ }else if(map.size == k){ max = Math.max(max,j-i + 1) j++ }else if(map.size > k){ while (map.size > k) { if(map.get(string[i]) > 0){ map.set(string[i],map.get(string[i]) - 1) }else{ map.delete(string[i]) } i++ } } } return max } console.log(solve(string,3)) console.log("hello world")
@PavanBilagi
@PavanBilagi 2 месяца назад
In kotlin fun longestSubStringWithKUniqueCharacters(s: String, k: Int): Int { val n = s.length var i = 0 var j = 0 var maxLength = Int.MIN_VALUE val uniqueCharMap = mutableMapOf() while (j < n) { uniqueCharMap[s[j]] = uniqueCharMap.getOrDefault(s[j], 0) + 1 if (uniqueCharMap.size < k) { j++ } else if (uniqueCharMap.size == k) { maxLength = Math.max(maxLength, j - i + 1) j++ } else if (uniqueCharMap.size > k) { while (uniqueCharMap.size > k) { if (uniqueCharMap.containsKey(s[i])) { uniqueCharMap[s[i]] = uniqueCharMap[s[i]]!!.minus(1) } if (uniqueCharMap[s[i]] == 0) { uniqueCharMap.remove(s[i]) } i++ j++ } } } if (maxLength == Int.MIN_VALUE) { return -1 } return maxLength }
@babai2196
@babai2196 Год назад
can any one tell me te time complexity
@yuggurnani1183
@yuggurnani1183 3 года назад
Solved it without watching the video....Thank u for such amazing teaching technique @adityaverma please leave a like
@shashankchaturvedi8697
@shashankchaturvedi8697 3 года назад
can u please share the code
@curtdudeanmol9393
@curtdudeanmol9393 3 года назад
@@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 3 года назад
@@curtdudeanmol9393 nice code bro
@mayank6023
@mayank6023 3 года назад
👍👍
@ravi54217
@ravi54217 Год назад
Implementation in Java. public class LongestSubstringWithKUniqueCharacters { public static void main(String[] args) { System.out.println(find("aabacbebebe", 3)); // 7 System.out.println(find("aaaa", 2)); // -1 } public static int find(String s, int k) { final int n = s.length(); Map map = new HashMap(); int i = 0, j = 0, answer = -1; while (j < n) { char currentChar = s.charAt(j); map.put(currentChar, map.getOrDefault(currentChar, 0) + 1); while (i k) { char c = s.charAt(i); map.put(c, map.get(c) - 1); if (map.get(c) < 1) map.remove(c); ++i; } if (map.size() == k) { answer = Math.max(answer, j - i + 1); } ++j; } return answer; } }
@neerajmahapatra5239
@neerajmahapatra5239 2 года назад
Java marjawa mitjawa... 😂😂😂
@biswarupacharjya2258
@biswarupacharjya2258 8 месяцев назад
#include using namespace std; int LongestSubstring_With_K_Unique_Characters(string &str, int k,int n){ unordered_map mp; int i=0;int j=0; int maxi=INT_MIN; while(jk){ mp[str[i]]--; if( mp[str[i]]==0){ mp.erase( str[i] ); } i++; } j++; } } return maxi; } int main() { coutk; int ans=LongestSubstring_With_K_Unique_Characters(s,k,n); cout
Далее
Variable Size Sliding Window General Format
15:38
Просмотров 114 тыс.
БЕЛКА ЗВОНИТ ДРУГУ#cat
00:20
Просмотров 788 тыс.
Вопрос Ребром - Серго
43:16
Просмотров 342 тыс.
FATAL CHASE 😳 😳
00:19
Просмотров 1,6 млн
Pick Toys |  An Interesting Sliding Window Problem
23:37
Ai Code Editors Are Ruining Tech
7:41
Просмотров 5 тыс.
Longest Substring Without Repeating Characters | Amazon
24:00
I gave 127 interviews. Top 5 Algorithms they asked me.
8:36
Maximum Sum Subarray of size K | Sliding Window
23:42
Просмотров 324 тыс.
БЕЛКА ЗВОНИТ ДРУГУ#cat
00:20
Просмотров 788 тыс.