Hi MIK I have cracked a product based company 🥳 and interviewers were impressed by my problem solving skills ☺️ and even now whenever I get stuck on any problem I prefer watching your solution video always. Thank you so much❤
I quickly predicted that it’s a sliding window problem but I got stuck on how to find min and max in the window efficiently. I tried heap but got stuck with window shrink. Here to learn from you ❤❤❤
I started watching your channel when there were only few subscribers around 6-7k. Now it's 76.3k, loved to see you growing. Keep up your good work! Your teaching skills are really invaluable.
Thanks bhaiya ...your explanation is really exceptional, the way you explain and build the approach to solve question from scratch and explain why we need a particular data structure. Mahadev Matarani bless you ♥
It's not optimal but coded it myself after watching till 14:02 ,feeling happy😊 Thanks MIK bhaiya 🙏 class Solution { public: bool valid(multiset & subarr){ int mini = *(subarr.begin()); int maxi = *(subarr.rbegin()); return maxi-mini
problems like these make me feel that I'll do it on my own next time. Wo sliding window ka problem mujhe ye hota ki while loop ke under sab code ka arrangement kaisa ho, like first while loop lagake shrink karna or first doing operations. Maybe not able to convey in words but less practice hai ismei. Lekin thanks great video!!!!
Somehow when I cannot solve a problem on my own, I open your video, listen to your motivation, think about it, and then magically multiple possible approaches start coming to my mind. I can solve that problem on my own (not always optimized, but fast enough to get accepted) and this problem was one such example. Here is my version of the solution: class Solution: def continuousSubarrays(self, nums: List[int]) -> int: i, count = 0, 1 maxList, minList = [(-nums[0], 0)], [(nums[0], 0)] for j in range(1, len(nums)): while maxList and abs(-maxList[0][0] - nums[j]) > 2: _, ind = heappop(maxList) i = ind+1 while minList and abs(minList[0][0] - nums[j]) > 2: _, ind = heappop(minList) i = ind+1 count += j-i+1 heappush(maxList, (-nums[j], j)) heappush(minList, ( nums[j], j)) return count
Thank you sir I'm consistently following your videos and recent days I felt i was able to approach problems in more better way I'm in my 2nd year , I think by the start of 3rd year I would be in a good form in DSA.
Maza agaya. Each second is so valuable in your videos. Also, I understood the monotonic approach and coded on my own in O(n). Thanks to you for improving my DSA
If we use normal queue data structure instead of Heap then we can acheive the time complexity of O(n). Use Monotonic Queue to maintain the max and min element in current window.
class Solution { public long continuousSubarrays(int[] nums) { long ans = 0; Deque min = new ArrayDeque(); Deque max = new ArrayDeque(); int i = 0; int n = nums.length; for (int j = 0; j < n; j++) { while (!min.isEmpty() && nums[min.peekLast()] > nums[j]) { min.pollLast(); } min.addLast(j); while (!max.isEmpty() && nums[max.peekLast()] < nums[j]) { max.pollLast(); } max.addLast(j); while (!min.isEmpty() && !max.isEmpty() && nums[max.peekFirst()] - nums[min.peekFirst()] > 2) { if (min.peekFirst() == i) { min.pollFirst(); } if (max.peekFirst() == i) { max.pollFirst(); } i++; } ans += j - i + 1; } return ans; } } Now it takes O(n) tc.
TLE -> 2134 / 2135 If anyone is trying to solve it using min max concept . class Solution { public: long long continuousSubarrays(vector& nums) { int n = nums.size(); int i = 0, j = 0; long long cnt = 0; int mini = nums[0], maxi = nums[0]; while (j < n) { mini = min(mini, nums[j]); maxi = max(maxi, nums[j]); while (maxi - mini > 2) { i++; mini = *min_element(nums.begin() + i, nums.begin() + j + 1); maxi = *max_element(nums.begin() + i, nums.begin() + j + 1); } cnt += (j - i + 1); j++; } return cnt; } };
@@utkarsh-k6p bc we will only find minimum element when minimum element is equal to the element which we are moving ahead I++, so that minimum element is removed now we need to find new element from the subbarr y which is between I and j also if ith element is not the minimum element so we don't need to again find the minimum since it's inside our window so this will save lot of time
here is my solution with O(1) space int n = nums.size(); int i=0,j=0; int mnidx = 0,mxidx = 0; int mnele = nums[0], mxele = nums[0]; long long int ans = 0; while(j 2 || abs(nums[j]-mxele) > 2){ mxele = nums[j], mnele = nums[j]; int k = j-1; while(k>=i){ mxele = max(mxele,nums[k]); mnele = min(mnele,nums[k]); if(abs(nums[k] - nums[j]) > 2) break; k--; } i = k+1; } ans += (j-i+1); mxele = max(mxele,nums[j]); mnele = min(mnele,nums[j]); j++; } return ans;
Approach 3: Using Segment Tree (Java Code below) class Solution { private int[] segTreeMin; private int[] segTreeMax; public void buildSegTreeMin(int[] nums, int i, int l, int r) { if (l == r) { segTreeMin[i] = nums[l]; return; } int lChild = (i
passed 1801/2135 test cases with this 😥😥: long long continuousSubarrays(vector& nums) { long long result = 0; int i=0; int j=0; while(j < nums.size()){ if(abs(nums[i] - nums[j])
Hii MIK, I have been solving questions for a while, But I am not able to identify testcase that would fail the program until I run it. This habit is causing problem in contest and OA as the test cases are hidden. How can i work on this issue?
How you got to know that size of map will never exceed 3 ?? One more questions, some problems have 4 to 5 solutions !! So do we need to check all the 4 to 5 solutions ? If we are in beginner to intermediate stage ?
Bhaiya how we can think about DP in this question , like in leetcode some have solved this problem using dp , like here we have to check continuos subarray so how we can apply take or not take condition ? i just want to know that how we can think about dp in such problems?
Is there any data Structure in java like ordered set / ordered map because in my mind when you say that the elements arranged automatically in increasing order then it is a concept of heap but it is not heap. Can you clarify ? Please... Which Data Structure we use in Java
You can use TreeMap. TreeMap freq = new TreeMap(); For Tree map you can use this condition: while (freq.lastEntry().getKey() - freq.firstEntry().getKey() > 2) {...}
Mazhar bhai, At 6:50, why did not we include {2,2}? This is also a valid subarray. Aksing this because at 3:47 you selected {5,2} but did not include because it not a valid subarray as per the contrains.
@@vaibhavshukla6911 Argh!! Now I get it. Actually Mazhar did not select {5,2}, but {5,4,2}. And this selected subarray {5,4,2} is invalid because of {'5', 4, '2'}. Thanks bhai.
Deques Are Better Here than Heap Optimal Time Complexity: Deques provide 𝑂(1) O(1) push and pop operations, ensuring the sliding window runs in linear time. Heaps, with 𝑂(log𝑛) O(logn) operations, introduce unnecessary overhead. Simplicity: Deques are straightforward to manage, while heaps require additional logic to handle outdated indices (e.g., lazy deletion or a hash map).
Solved it using your khandani sliding window template. Thanks MIK
Ye hui na baaaaat ❤️❤️❤️🔥🔥🔥
Hi MIK I have cracked a product based company 🥳 and interviewers were impressed by my problem solving skills ☺️ and even now whenever I get stuck on any problem I prefer watching your solution video always. Thank you so much❤
can you guide how ..
can you guide how ..
@@bhanubediya4521 on campus or off campus?
congrats man.
Many Many Congratulations 🎉🎉🙌🙌❤️❤️
I quickly predicted that it’s a sliding window problem but I got stuck on how to find min and max in the window efficiently. I tried heap but got stuck with window shrink.
Here to learn from you ❤❤❤
Better than watching 1hr webseries's episodes❤️
You are best tutor on youtube for DSA. I have watched many over the years, but no one explains building the approach better than you.
This means a lot ❤️🙏
I started watching your channel when there were only few subscribers around 6-7k. Now it's 76.3k, loved to see you growing. Keep up your good work! Your teaching skills are really invaluable.
Mik I got a job offer at an amazing American company. Major thanks to you
Congratulations bro . Do share your preparation strategy
kal leetcode 1438 dekha tha apka , aj vala same he to , khud se kar liya , THANKSSS
Thanks bhaiya ...your explanation is really exceptional, the way you explain and build the approach to solve question from scratch and explain why we need a particular data structure.
Mahadev Matarani bless you
♥
thanku... .. u r literally legend for us❤solved on my own but need to see the vdo to learn from u
This means a lot to me ❤❤
@@codestorywithMIK pls make video on sweep line algo and on contest 4th questions of previous week weekly and biweekly contests plzzzzz
It's not optimal but coded it myself after watching till 14:02 ,feeling happy😊
Thanks MIK bhaiya 🙏
class Solution {
public:
bool valid(multiset & subarr){
int mini = *(subarr.begin());
int maxi = *(subarr.rbegin());
return maxi-mini
I love 2nd approach ❤
Thanks bhaiya, Now i getting approaches to solve these type of questions by self
watched till 21:15, then coded myself.....legend mik 🔥
🙌🙌🙌
@codestorywithMIK thank u so much bhaiya
U don't know your daily problems are changing many lives like me❤️❤️❤️
problems like these make me feel that I'll do it on my own next time. Wo sliding window ka problem mujhe ye hota ki while loop ke under sab code ka arrangement kaisa ho, like first while loop lagake shrink karna or first doing operations. Maybe not able to convey in words but less practice hai ismei.
Lekin thanks great video!!!!
Great video , your style of writing code like story to code is awsome. i have started thinking in the same way . Lots of thans MIK.
nicely expained
Somehow when I cannot solve a problem on my own, I open your video, listen to your motivation, think about it, and then magically multiple possible approaches start coming to my mind. I can solve that problem on my own (not always optimized, but fast enough to get accepted) and this problem was one such example. Here is my version of the solution:
class Solution:
def continuousSubarrays(self, nums: List[int]) -> int:
i, count = 0, 1
maxList, minList = [(-nums[0], 0)], [(nums[0], 0)]
for j in range(1, len(nums)):
while maxList and abs(-maxList[0][0] - nums[j]) > 2:
_, ind = heappop(maxList)
i = ind+1
while minList and abs(minList[0][0] - nums[j]) > 2:
_, ind = heappop(minList)
i = ind+1
count += j-i+1
heappush(maxList, (-nums[j], j))
heappush(minList, ( nums[j], j))
return count
So happy to know this ❤️❤️❤️
Waiting for this video! Thanks!
Appreciate the wait, hope you find it useful! 🙏
resuming my dsa practice after diwali
Thank you sir
I'm consistently following your videos and recent days I felt i was able to approach problems in more better way
I'm in my 2nd year , I think by the start of 3rd year I would be in a good form in DSA.
Sir, please make explanation videos on Leetcode Contest questions. Especially on 3rd or 4th question.
We can also use multiset in place of ordered map as it can store dupplicate elements and store elements in sorted manner
Indeed ❤️
Maza agaya. Each second is so valuable in your videos.
Also, I understood the monotonic approach and coded on my own in O(n). Thanks to you for improving my DSA
your explanation is just wow🎉🎉 why do we need that data structure it is the main thing ❤
was waiting. The Legend is here.
If we use normal queue data structure instead of Heap then we can acheive the time complexity of O(n). Use Monotonic Queue to maintain the max and min element in current window.
class Solution {
public long continuousSubarrays(int[] nums) {
long ans = 0;
Deque min = new ArrayDeque();
Deque max = new ArrayDeque();
int i = 0;
int n = nums.length;
for (int j = 0; j < n; j++) {
while (!min.isEmpty() && nums[min.peekLast()] > nums[j]) {
min.pollLast();
}
min.addLast(j);
while (!max.isEmpty() && nums[max.peekLast()] < nums[j]) {
max.pollLast();
}
max.addLast(j);
while (!min.isEmpty() && !max.isEmpty() && nums[max.peekFirst()] - nums[min.peekFirst()] > 2) {
if (min.peekFirst() == i) {
min.pollFirst();
}
if (max.peekFirst() == i) {
max.pollFirst();
}
i++;
}
ans += j - i + 1;
}
return ans;
}
}
Now it takes O(n) tc.
Definitely yes ❤️
truly legend
Thanks a lot bhaiya ❤❤
TLE -> 2134 / 2135
If anyone is trying to solve it using min max concept .
class Solution {
public:
long long continuousSubarrays(vector& nums) {
int n = nums.size();
int i = 0, j = 0;
long long cnt = 0;
int mini = nums[0], maxi = nums[0];
while (j < n) {
mini = min(mini, nums[j]);
maxi = max(maxi, nums[j]);
while (maxi - mini > 2) {
i++;
mini = *min_element(nums.begin() + i, nums.begin() + j + 1);
maxi = *max_element(nums.begin() + i, nums.begin() + j + 1);
}
cnt += (j - i + 1);
j++;
}
return cnt;
}
};
by using if statement u can save some time so it will pass:
bool valid(int val1, int val2){
return val2>=0&&val2=0&&val1
@batuklal yup It is Accepted now ... Can u explain why u write like mini==nums[i-1]
@@utkarsh-k6p bc we will only find minimum element when minimum element is equal to the element which we are moving ahead I++, so that minimum element is removed now we need to find new element from the subbarr y which is between I and j also if ith element is not the minimum element so we don't need to again find the minimum since it's inside our window so this will save lot of time
well explained.
yes mik bhyia i am ready for see the best side of me and a new more hardworking o person in 2025.
Let’s do it ❤️❤️❤️
Amazing
First Comment ❤❤❤❤❤❤❤❤❤❤
Appreciate it! 🙏❤️
@@codestorywithMIK Thank you Sir ❤❤❤❤❤❤❤❤❤❤
It would be great if you can make a video on O(n) approach of this
Bhaiya ispe video bnaa do jra .
3116. kth smallest amount with single denomination combination
Thankyou
Used monotonic increasing and decreasing deque. That gives n time complexity.
Perfect 👌❤️
here is my solution with O(1) space
int n = nums.size();
int i=0,j=0;
int mnidx = 0,mxidx = 0;
int mnele = nums[0], mxele = nums[0];
long long int ans = 0;
while(j 2 || abs(nums[j]-mxele) > 2){
mxele = nums[j], mnele = nums[j];
int k = j-1;
while(k>=i){
mxele = max(mxele,nums[k]);
mnele = min(mnele,nums[k]);
if(abs(nums[k] - nums[j]) > 2) break;
k--;
}
i = k+1;
}
ans += (j-i+1);
mxele = max(mxele,nums[j]);
mnele = min(mnele,nums[j]);
j++;
}
return ans;
we can use multiset as well
Approach 3: Using Segment Tree (Java Code below)
class Solution {
private int[] segTreeMin;
private int[] segTreeMax;
public void buildSegTreeMin(int[] nums, int i, int l, int r) {
if (l == r) {
segTreeMin[i] = nums[l];
return;
}
int lChild = (i
passed 1801/2135 test cases with this 😥😥:
long long continuousSubarrays(vector& nums) {
long long result = 0;
int i=0;
int j=0;
while(j < nums.size()){
if(abs(nums[i] - nums[j])
Hi, can you tell me which tool are you using for explaining the solution?
bhaiya if possible can you make a video on
2850. Minimum Moves to Spread Stones Over Grid
recursion and backtracking approach.
Mik bhai can you please make a video on this question : 1588. Sum of All Odd Length Subarrays
Let me plan that soon ❤️
Can you plz tell the time complexity of inserting any key value pair in TreeMap vs HashMap in java?
v good soluti0n sir
Can it be solved using two monotone deque maintaining max and minimum elements in a window.???
Is there a way to implement the first approach using python while keeping the time complexity linear?
miku bhiyaa pls try solving lc 1712 a very standard questn of prefixsum+binary search pls do solve that
hello Mik bhaiya ,I hope this reaches you , please make a video of o(1) space complexity soln
Let me plan soon ❤️
Hii MIK,
I have been solving questions for a while, But I am not able to identify testcase that would fail the program until I run it. This habit is causing problem in contest and OA as the test cases are hidden. How can i work on this issue?
maine simple sliding window se kiya to bs 10 test case me tle de diya😥😥
Tried brute force stuck at 1630/2134 😅
So glad to see you tried brute force first ❤️
How you got to know that size of map will never exceed 3 ??
One more questions, some problems have 4 to 5 solutions !! So do we need to check all the 4 to 5 solutions ? If we are in beginner to intermediate stage ?
Bhaiya how we can think about DP in this question , like in leetcode some have solved this problem using dp , like here we have to check continuos subarray so how we can apply take or not take condition ? i just want to know that how we can think about dp in such problems?
Is there any data Structure in java like ordered set / ordered map because in my mind when you say that the elements arranged automatically in increasing order then it is a concept of heap but it is not heap. Can you clarify ? Please...
Which Data Structure we use in Java
You can use TreeMap.
TreeMap freq = new TreeMap();
For Tree map you can use this condition:
while (freq.lastEntry().getKey() - freq.firstEntry().getKey() > 2) {...}
Mazhar bhai, At 6:50, why did not we include {2,2}? This is also a valid subarray.
Aksing this because at 3:47 you selected {5,2} but did not include because it not a valid subarray as per the contrains.
Bcz subarray is contiguous
@@vaibhavshukla6911 Argh!! Now I get it.
Actually Mazhar did not select {5,2}, but {5,4,2}. And this selected subarray {5,4,2} is invalid because
of {'5', 4, '2'}.
Thanks bhai.
you said 1+2+3 = 7 at 7:22
Apologies for silly mistake. 😇
Deques Are Better Here than Heap
Optimal Time Complexity: Deques provide 𝑂(1)
O(1) push and pop operations, ensuring the sliding window runs in linear time. Heaps, with 𝑂(log𝑛)
O(logn) operations, introduce unnecessary overhead.
Simplicity: Deques are straightforward to manage, while heaps require additional logic to handle outdated indices (e.g., lazy deletion or a hash map).
but bhaiya frequency ka koiuse nhi hai