Тёмный

L7. Number of Substrings Containing All Three Characters | 2 Pointers and Sliding Window Playlist 

take U forward
Подписаться 597 тыс.
Просмотров 25 тыс.
50% 1

Notes/Codes/Problem links under step 10 of A2Z DSA Course: takeuforward.org/strivers-a2z...
Entire playlist: • Two Pointer and Slidin...
Follow us on our other social media handles: linktr.ee/takeuforward

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

 

25 мар 2024

Поделиться:

Ссылка:

Скачать:

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

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 58   
@artofwrick
@artofwrick 3 месяца назад
These questions are very important for contests . The first question is always a string question where you have to generate subarray. For arrays, questions from PREFIX sum comes often
@sauravkumar-ln7zh
@sauravkumar-ln7zh 12 дней назад
i did this question based on the logic based on previous question → We need to monitor every character in the sliding window. → For this, we use a map to keep track of the number of each character present in the sliding window. → If the number of distinct characters exceeds k, we start removing characters from the back until the size of the map is less than or equal to k. → If the count of a certain character becomes zero while removing it from the back, we must erase it from the map to decrease the map's size. class Solution { public: int plzhelp(string s, int k) { int i = 0; int j = 0; unordered_map mp; int count = 0; while (j < s.length()) { mp[s[j]]++; while (mp.size() > k) { mp[s[i]]--; if (mp[s[i]] == 0) { mp.erase(s[i]); } i++; } count += (j - i + 1); j++; } return count; } int numberOfSubstrings(string s) { int k = 3; int count = plzhelp(s, k) - plzhelp(s, k - 1); return count; } };
@sauravdhar1696
@sauravdhar1696 4 дня назад
can you explain why you did => int count = plzhelp(s, k) - plzhelp(s, k - 1) ??
@Rahul_Mongia
@Rahul_Mongia 3 дня назад
@@sauravdhar1696 kyo ki plzhelp(s,k) will return all substring having characters
@namannema3349
@namannema3349 2 месяца назад
i hope striver one day i will build logic like you
@rajalakshmis7308
@rajalakshmis7308 2 месяца назад
Thank you, Striver. Before watching this video, I just solved it using your previous lecture pattern. But, the approach you used is the best among all. import java.util.HashMap; public class Solution { public static int countSubstring(String s){ // Write your code here. // to find the tot subarray count int res = s.length()*(s.length()+1)/2; // return tot subarray - subarray which has atmost any 2 characters from a,b,c. return res-solve(s); } // function to find a subarray which has atmost any 2 character from a,b,c public static int solve(String s){ HashMap map = new HashMap(); int left=0,count=0; for(int right=0;right2){ map.put(s.charAt(left), map.get(s.charAt(left))-1); if(map.get(s.charAt(left))==0) map.remove(s.charAt(left)); left++; } count+=right-left+1; } return count; } }
@2amCoder
@2amCoder 3 месяца назад
the reason you were good at cp. i tried many things with this solution but none of them were close good as this last explanation
@user-kx1sv7lq4k
@user-kx1sv7lq4k Месяц назад
I was not able to understand this question's approach but you have done it :)
@mayank_singh_43
@mayank_singh_43 8 дней назад
This problem of counting substring and subarrays always confused me in any contest , now I learned the concept of how to do this. THanks a lot striver bhaiya
@ratishjain2718
@ratishjain2718 2 месяца назад
insane approach
@Adarsh-fg5gs
@Adarsh-fg5gs Месяц назад
i did somewhat diffrent as TOtal no of subarrays - subarrays with at most 2 distinct characters and it becomes same as previous question int countSubstring(string s) { //Total no of subarrays with n characters =n(n+1)/2 int n=s.size(); int total=n*(n+1)/2; //now write code to find for at most 2 distinct characters int acnt=0,bcnt=0,ccnt=0,res=0,l=0,r=0; while(r0 && bcnt>0 && ccnt>0){ if(s[l]=='a')acnt--; if(s[l]=='b')bcnt--; if(s[l]=='c')ccnt--; l++; } res+=(r-l+1); r++; } return total-res; //total no of subarrays-subarrys with at most two distinct }
@rlm3227
@rlm3227 19 дней назад
The optimised solution is a very clever sol
@ManishKumar-dk8hl
@ManishKumar-dk8hl 3 месяца назад
optimal :- class Solution { public int numberOfSubstrings(String s) { int len=0; int r=0; int[] arr=new int[3]; Arrays.fill(arr,-1); while(r
@Arya20012
@Arya20012 2 месяца назад
what a grate solution,just love this,thank u brother
@cheezy_cheez
@cheezy_cheez Месяц назад
best explanation! especially the part where you mentioned why even omiting the if checking would be ok, I was bamboozled haha
@sunitsable2752
@sunitsable2752 Месяц назад
amazing logic!!!
@KratiGarg-ue1ph
@KratiGarg-ue1ph Месяц назад
I tried the approach you gave in the binary subarray question (number of total subarrays(n*(n+1)/2) - the subarrays where mapcount < 3. that also worked. Please give tips on how to approach a question like this!
@abhinayrk985
@abhinayrk985 Месяц назад
Outstanding
@codeman3828
@codeman3828 2 месяца назад
Understood. great
@subee128
@subee128 3 месяца назад
Thanks
@moonlight-td8ed
@moonlight-td8ed 10 дней назад
mind blown dude... crazy optimal soln
@ujjwalkashyap9196
@ujjwalkashyap9196 3 месяца назад
Please update the site also with all the upcoming videos 🙏
@techyguyaditya
@techyguyaditya 2 месяца назад
This took a bit of time to understand for optimal approach. I was literally trying to derive mathematical formula which only passes the test case shown in video, further optimizing the code. But the edge case is that, L may not update in other test cases. Basic approach: Find left value of minimum sliding window in each iteration (start finding once a,b,c gets it's value other than -1). Then basically, for each iter, ctr += 1 + L (where L is leftmost index of window, min(a,b,c)). Striver said to omit if statement, because 1 + (-1) = 0. I disagree with that, because if you see low level programming, the unnecessary write operation happens to the memory even if the value remains the same. Write operations are generally considered as costly operation. Even if it's for 1 extra line of code, it will prevent the costly write operation just by having read operation, further optimizing the code.
@square-kstudios9561
@square-kstudios9561 2 месяца назад
Great explanation! How does one come up with a solution like this in the constraints of an interview though, if we haven't seen it ever in the past? Some companies only give you 15 mins to come up with a solution, explain it, dry run it, code it and then provide the time/space complexity.
@ajithshetty1684
@ajithshetty1684 Месяц назад
did you get the answer to your question?
@shivisingh9975
@shivisingh9975 2 месяца назад
Understood!
@tanishqtyagi1465
@tanishqtyagi1465 28 дней назад
The series is dam good!! 🤍🤍💯
@aamna5243
@aamna5243 3 месяца назад
bhai farishta h tu.
@ayanahmad12
@ayanahmad12 3 месяца назад
Literally 🔥✅
@PawanKumar-tj2xk
@PawanKumar-tj2xk 22 дня назад
@@ayanahmad12 simp
@dipendrasingh4874
@dipendrasingh4874 2 месяца назад
thank you bhaiya ... please tcs nqt segment i was solving them but u removed that from site .....(or i am not able to find it )please add thank you
@adilkevin6220
@adilkevin6220 2 месяца назад
Document link is not attached for some of the program
@RonitTejani
@RonitTejani 6 дней назад
Legit God
@Flash-qr5oh
@Flash-qr5oh Месяц назад
WoW!
@sobhansahoosubh3873
@sobhansahoosubh3873 5 дней назад
we also do like this way int numberOfSubstrings(string s) { int n = s.size(); int l = 0,r = 0,count = 0; unordered_map mp; while(r < n) { mp[s[r]]++; while(mp['a'] >= 1 && mp['b'] >= 1 && mp['c'] >= 1 ) { count = count + (n - r); mp[s[l]]--; l++; } r++; } return count; }
@angeldeveloper
@angeldeveloper 3 месяца назад
❤👍
@socify4410
@socify4410 Месяц назад
fabolous
@animexworld6614
@animexworld6614 3 месяца назад
My question is what is your favorite colour
@saakshishekhar237
@saakshishekhar237 3 месяца назад
int numberOfSubstrings(string s) { vector lastSeen(3,-1); int cnt = 0; for(int i=0; i
@sakethsenapathi8323
@sakethsenapathi8323 3 месяца назад
i didnt get what is lastseen[s[i] - 'a'] = i part can u please explain.
@ManishKumar-dk8hl
@ManishKumar-dk8hl 3 месяца назад
@@sakethsenapathi8323 s[i] character represent kr raha h aur jb unme 'a' minus hoga too a-a=0 ; b-a=1 ;c-a =2 ayega then lastseen wali array k index pr string k character ka index store hoyega . index 0 of array=a, index 2= b,index 2=c
@doremon81072
@doremon81072 Месяц назад
demm man
@omkarsawant9267
@omkarsawant9267 День назад
#include #include #include #include using namespace std; // Function to count the number of substrings containing all three characters 'a', 'b', and 'c' pair numberOfSubstrings(string s) { // Hashmap to store the count of 'a', 'b', and 'c' in the current window unordered_map count; int left = 0, result = 0; vector substrings; // Iterate over the string with 'right' as the end of the window for (int right = 0; right < s.length(); ++right) { // Increment the count of the current character count[s[right]]++; // Check if all three characters are present in the current window while (count['a'] > 0 && count['b'] > 0 && count['c'] > 0) { // If yes, add all possible substrings starting from the current 'left' to 'right' result += s.length() - right; // Capture the substrings for (int k = right; k < s.length(); ++k) { substrings.push_back(s.substr(left, k - left + 1)); } // Move the left end of the window to the right count[s[left]]--; left++; } } return {result, substrings}; } int main() { string s = "abcabc"; auto result = numberOfSubstrings(s); cout
@CE_113_Katyayni
@CE_113_Katyayni 2 месяца назад
sir your brute force approach is actually wrong because when we sum the hash[0]+hash[1]+hash[2] ==3 here it may be the case that hash[1]=0 and hash[0]=2 in this case also the if state would be true and cnt will increase which is actually wrong
@rohitvishwakarma7046
@rohitvishwakarma7046 2 месяца назад
Yeah, I think he meant to take the size of hashmap , hope you get it.
@azizkavas6993
@azizkavas6993 2 месяца назад
No such case is possible because hash doesnt count the number of occurance instead it just sign the related index. If you try yourself with sample code you will see what I mean. Kind regards.
@ashnidahiya8347
@ashnidahiya8347 4 дня назад
This is a brute force approach using sets, hope it helps: int countSubStrings(string str, int k) { set st; int count = 0; int n = str.length(); for(int i=0;i
@nirbhaysingh7971
@nirbhaysingh7971 3 месяца назад
#include int countSubstring(string s){ // Write your code here. int n = s.size(); int left = 0; int right = 0; map mpp; int cnt = 0; while(right
@user-fw4kz3bb4g
@user-fw4kz3bb4g Месяц назад
EASIEST APPROACH (C++) class Solution { public: int numberOfSubstrings(string s) { int left=0, right=0,count=0; vectorarr(3,0); while(right0 && arr[1]>0 && arr[2]>0){ count+=s.size()-right; arr[s[left]-'a']--; left++; } right++; } return count; } };
@Bhai9866
@Bhai9866 2 месяца назад
public int numberOfSubstrings(String s) { int[] lastSeen = new int[3]; Arrays.fill(lastSeen, -1); int cnt = 0; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); lastSeen[c - 'a'] = i; if (lastSeen[0] != -1 && lastSeen[1] != -1 && lastSeen[2] != -1) { cnt += (1 + Math.min(lastSeen[0], Math.min(lastSeen[1], lastSeen[2]))); } } return cnt; }
@KartikeyTT
@KartikeyTT 2 месяца назад
If someone can debug this solution then they are real genius class Solution { public: int numberOfSubstrings(string s) { map map; int l = 0; int r = 0; int count = 0; int minValue=0; while (map.size() != 3) { map[s[r]] = r; r++; } while (r < s.length()) { minValue=INT_MAX; for (const auto& pair : map) { cout
@ShubhamMIshra-hv5nz
@ShubhamMIshra-hv5nz 2 месяца назад
CODE FOR THEOPTIMISED SOLUTION!!!!! class Solution { public: int numberOfSubstrings(string s) { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int count =0; int length=s.size(); int lastSceen[3]={-1,-1,-1}; for(int i =0; i < length; i++){ lastSceen[s[i]-'a']=i; if(lastSceen[0] != -1 && lastSceen[1]!= -1&& lastSceen[2]!=-1) { count += min(lastSceen[0],min(lastSceen[1],lastSceen[2])) +1; } } return count; } }; whats up??
@anmolvanced3262
@anmolvanced3262 8 дней назад
viewed multiple times .. but your explanation is not good .. sorry to say!
@KartikeyTT
@KartikeyTT 2 месяца назад
If you want to find minimum of three elements in cpp. You can do it like this- int temp = min(arr[0],arr[1]); int lowestI = min(temp, arr[2]);
@AnujGupta-xi5ep
@AnujGupta-xi5ep 2 месяца назад
For one liner you can do : int ans = min({arr[0], arr[1], arr[2]});
@KartikeyTT
@KartikeyTT 2 месяца назад
@@AnujGupta-xi5ep ohhh, i was doin without the braces and was getting error, so i thought it wasn’t possible in cpp
@adityababu3405
@adityababu3405 11 дней назад
int numberOfSubstrings(string s) { vector lastSeen(3,-1); int cnt = 0; for(int i=0; i
Далее
WHY did this C++ code FAIL?
38:10
Просмотров 187 тыс.
▼ЧЁРНАЯ МАГИЯ 🔮
31:15
Просмотров 324 тыс.
skibidi toilet multiverse 039 (part 1)
05:29
Просмотров 6 млн
10 Math Concepts for Programmers
9:32
Просмотров 1,8 млн
▼ЧЁРНАЯ МАГИЯ 🔮
31:15
Просмотров 324 тыс.