I couldn't understand this problem's solution even after reading several leetcode discuss posts. However, I understood this completely at once after watching your video! Thanks!
kudos to your patience while explaining sir.The way of you instruct the solution to the problem was quite appealing, unlike some other youtubers who just write the code in rush without explaining properly. Thanks again
Sliding Window Approach with Monotonic Queue The idea is to keep the maximum number in the sliding window at the front of the Deque and the possible maximum numbers at the rear end (last) of the queue. The Deque would have numbers sorted in descending order, front having the maximum number and rear would have the smallest in the current window. As we iterate over the array if num[i] is greater than the smallest number of current window than we start removing the numbers as long as num[i] is greater than number in the window. Also we add the index of current number in Deque as this number could be possible maximum as the window slides to the right. We could have tried to use Stack or PriorityQueue to keep track of maximum in the current window, but we don't only need to track maximum number in the current window but also other numbers (possible maximum) which are less than maximum number in the current window. Because as we move to the next window, these possible maximum numbers might become the maximum number in that window. Choosing the right Data Structure : Double Ended Queue (Deque) If we use Stack, we can only get access to the top element, for accessing other elements we would have to pop the elements from the stack and would have to push it back to stack. Similarly if we use PriorityQueue we can only get access to the min or max element which is at the top of heap, for accessing other elements we would have to remove elements from the heap and would have to push it back to heap. A Double ended Queue allows us to perform operation on both the ends of the data structure and we can easily access the elements in Deque. We could have used Doubly Linked List as well but the problem is, it lacks the ease of access to perform operation or access elements from both the front and rear end. In Java Deque gives us methods e.g. addFirst(), addLast(), removeFirst(), removeLast(), peekFirst(), peekLast() to easily access the front/rear element and also start traversal from the front or rear. Important Points : We store the index i in Deque and not num[i], this is because we also have to remove numbers from the Deque as window slides to the right. We can check if index is out of current window we remove the number. For given window of K, remember we don't try to store k elements in the Deque, rather we just need to keep the maximum number at the front of Deque and add the current number at the rear end of Deque. And when we remove element from Deque we start from the rear end of Deque.
I don’t get the intuition that whenever we remove leftmost index from our window to go to the next window, why the left most index will also be the left most element in the deque (so we just remove the first element from our deque). In my thinking, I should loop through the deque to find the index to remove for every window.
The deque always contains elements in non-increasing order. In other words, deque head always be the greatest element of the window. Thus, when we from move from window [i, i+k-1] to [i+1, i+k], we only need to check if arr[i] (element getting ejected from the window) is at the head or not. It will always be at head if it is present in the deque while it is being ejected. Think like this, if there is an element at index j in the window [i, i+k-1] where arr[j]>arr[i], then while inserting j in the deque i would have been removed. Thus if index i is being ejected, then i could only present in the deque only at head.
I just had an interview with Google today and this was the algorithm I was given. That's why I'm here Haha. I was able to do it, but I took a different approach.
@@alokesh985 if i am not wrong in doubly linked list one can access,insert and pop elements at any position but in deque one can do it only at front and back
Very great explanation. Thank you bhaiya for helping out the students but I have one suggestion pls upload videos on regular basis. I know u are very busy but it will be helpful for students who are appearing in this placement season. We have found the solution of dse sheet from anywhere but the video explanation of yours is very helpful to remember the concepts and do similar type questions on particular algorithms.
Worst case occurs when k = 1 , Inserting all N element and N-1 elements will be removed. This is because for each array element two operation DELETION -> INSERTION IS PERFORMED .
Respect for Aditya verma increased after this lecture 🙇♀️🙇♀️ I thought Raj Bhaiya would break the record of his explanation, but he is still unbeatable.
Is there any algorithm related to next greatest element or next smallest element, like how to devise algorithms for these type of problems, how to know we need a deque in this case as we do operations on both sides here?
There's another solution of this using next greater element approach, saw it here th-cam.com/video/tCVOQX3lWeI/w-d-xo.html as i was also thinking of applying nge algorithm.
The part that confuses me is dq.empty() or dq.front(), i thought they return a value at the index not the index itself. So how is it used here that it is checking the index and not the value? I am so confused.
Is the time complexity , really O(n) here ??.... because, if we take example, 6,4,5,3,2 with window size k =3, then once the greatest element 6 is removed, the next greatest element that is 5 should be placed at top, and for doing that worst case, there will be (k-1) comparisons. Anybody please correct me if I am wrong .
It can also be solved using Stack by finding Next Greater to Right: vector maxSlidingWindow(vector& nums, int k) { int n = nums.size(); stack stk; stk.push(n-1); vector ngr(n, 0); ngr[n-1] = INT_MAX; for (auto i=n-2; i>=0; i--){ while (! stk.empty() && nums[stk.top()]
Ur explanation is so awesome.. It's really helpful to us..🙏 can you please upload the video of 862. Leetcode problem Shortest subarray with Sum at Least K.🙏🙏 please sir please I'm really stuck in this problem.
Ur explanation is so awesome.. It's really helpful to us..🙏 can you plzz upload the video of 862. Leeetcode problem Shortest Subarray with Sum at Least K.🙏🙏 please sir please I'm really stuck in this prblm.
If you understand it, please do like it, and if possible please spare 2 seconds for a comment :)
make videos on dp please
What's the difference between deque and list?
16:22 smaller than equal to is not ok!!
only smaller than will be ok striver.
i don't know why anyone didn't point this out.
@@PrinceKumar-el7ob It would work. Try some test cases.
The best explanation on sliding window
This explanation literally made me overcome my fear of stacks and queues. Thank you so much!
Ya exactly..... I also have fear of stack and queue.. Even though they are quite easy to understand.
How one question can over come your fear? 🤔🤔🤔🤔
I got this question in a Microsoft interview for SDE 1
Is it offcampus or oncampus
@@kingmaker9082 Off campus
@@zetro6311 from where u applied for Microsoft or have u got any referral? Plz guide me...btw what is the result of interview bro?
@@kingmaker9082 hello bro? which batch are you?
@@vinyass3733 23 batch
I couldn't understand this problem's solution even after reading several leetcode discuss posts. However, I understood this completely at once after watching your video! Thanks!
kudos to your patience while explaining sir.The way of you instruct the solution to the problem was quite appealing, unlike some other youtubers who just write the code in rush without explaining properly.
Thanks again
bro getting harsh with apna collegeg
THank you bro.
Brute force+Optimized+code explanation---->complete video.
Thanks a ton.
Sliding Window Approach with Monotonic Queue
The idea is to keep the maximum number in the sliding window at the front of the Deque and the possible maximum numbers at the rear end (last) of the queue. The Deque would have numbers sorted in descending order, front having the maximum number and rear would have the smallest in the current window.
As we iterate over the array if num[i] is greater than the smallest number of current window than we start removing the numbers as long as num[i] is greater than number in the window.
Also we add the index of current number in Deque as this number could be possible maximum as the window slides to the right.
We could have tried to use Stack or PriorityQueue to keep track of maximum in the current window, but we don't only need to track maximum number in the current window but also other numbers (possible maximum) which are less than maximum number in the current window. Because as we move to the next window, these possible maximum numbers might become the maximum number in that window.
Choosing the right Data Structure : Double Ended Queue (Deque)
If we use Stack, we can only get access to the top element, for accessing other elements we would have to pop the elements from the stack and would have to push it back to stack.
Similarly if we use PriorityQueue we can only get access to the min or max element which is at the top of heap, for accessing other elements we would have to remove elements from the heap and would have to push it back to heap.
A Double ended Queue allows us to perform operation on both the ends of the data structure and we can easily access the elements in Deque. We could have used Doubly Linked List as well but the problem is, it lacks the ease of access to perform operation or access elements from both the front and rear end. In Java Deque gives us methods e.g. addFirst(), addLast(), removeFirst(), removeLast(), peekFirst(), peekLast() to easily access the front/rear element and also start traversal from the front or rear.
Important Points :
We store the index i in Deque and not num[i], this is because we also have to remove numbers from the Deque as window slides to the right. We can check if index is out of current window we remove the number.
For given window of K, remember we don't try to store k elements in the Deque, rather we just need to keep the maximum number at the front of Deque and add the current number at the rear end of Deque. And when we remove element from Deque we start from the rear end of Deque.
It is always challenging as well as fun to learn the optimal solution. But, your explanation helps a lot to understand it better.
I don’t get the intuition that whenever we remove leftmost index from our window to go to the next window, why the left most index will also be the left most element in the deque (so we just remove the first element from our deque). In my thinking, I should loop through the deque to find the index to remove for every window.
The deque always contains elements in non-increasing order. In other words, deque head always be the greatest element of the window. Thus, when we from move from window [i, i+k-1] to [i+1, i+k], we only need to check if arr[i] (element getting ejected from the window) is at the head or not. It will always be at head if it is present in the deque while it is being ejected.
Think like this, if there is an element at index j in the window [i, i+k-1] where arr[j]>arr[i], then while inserting j in the deque i would have been removed. Thus if index i is being ejected, then i could only present in the deque only at head.
Please increase the frequency of uploads as this is PLACEMENT SEASON
What a explanation 😯...I think this is the best video of window problem in TH-cam... Thank you so much for this great video....
I just had an interview with Google today and this was the algorithm I was given. That's why I'm here Haha. I was able to do it, but I took a different approach.
Much better explanation than in the new playlist !
Best Explanation. Thank you so much. Finally understood the use of deque for this problem.
Good explanation. That's an art which is rare. Every one knows the steps and code and solution, But very few know the explanation and intution
Waiting for tree series :)
easiest solution by naiveApproach
vector maxSlidingWindow(vector arr,int k){//TLE
vector ans;
int n= arr.size();
for (int i = 0; i < n-k+1; i++)
{
ans.push_back(*max_element(arr.begin()+i,arr.begin()+i+k)); // T.C = O(n) max_element
}
return ans;
}
Such a Nice Explanation even a beginner can understand. Thanks a lot
Very good explaination , though i have to see it 2 times to completely understand the concept👍
at 3:48 , deque should be Double ended queues I guess and not doubly linked list , btw nice explanation :)
I think he meant that double-ended queues are typically implemented using doubly linked lists
@@alokesh985 if i am not wrong in doubly linked list one can access,insert and pop elements at any position but in deque one can do it only at front and back
Can't find a better explanation than this for a hard problem.. simple love it
you can do by using a multiset as well , it takes nlogn but its very simple to write the code
This question can also be solve using heap
Waiting for tree series eagerly.
Placement already started in college, and tree , dp, strings remaining from the sheet
UNDERSTOOD..........Thank You So Much for this wonderful video...........🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻
Very great explanation. Thank you bhaiya for helping out the students but I have one suggestion pls upload videos on regular basis. I know u are very busy but it will be helpful for students who are appearing in this placement season. We have found the solution of dse sheet from anywhere but the video explanation of yours is very helpful to remember the concepts and do similar type questions on particular algorithms.
you are amazing God bless you. I wanna become like you one day
Worst case occurs when k = 1 , Inserting all N element and N-1 elements will be removed. This is because for each array element two operation DELETION -> INSERTION IS PERFORMED .
Thanks man I was doubtful about the On complexity. your explanation cleared it :)
Godly explanation. Suddenly, this problem does not look Leetcode Hard level
Understood Thanks Striver , I am suffering from health issues , Still not giving up.
This can also be solved using multiset, can we use multiset in the interview bhaiya?
That definitely not at 5:15 reminds me of Dhoni xD.
Great Explanation!
*Brute force*
class Solution {
public:
vector maxSlidingWindow(vector& nums, int k) {
vectorans;
int n = nums.size();
for(int i=0; i
Bhai when your course starts in unacademy pls update waiting for your course
Python simple one
x=[1,3,-1,-3,5,3,6,7]
k=3
y=[]
for i in range(len(x)-2):
y.append(max(x[i:i+k]))
print(y)
good explanation, thank you.
How about using Max Heap with size K.. time complexity will be NLogN i guess.. Space complexity will be O(K)
the flow of teaching is amazing bor
bhaiya please bring more videos fast fast .. placements are starting!!
Could not understand completely, but will come back
Bhaiya please make a video on the question: Find maximum of minimum for all the window sizes.
Bro can u please make a video on how to deal with large numbers and what exactly 10^9+7.
I just like every video of yours becuz your's are really gona help.
Great Explanation ! Thanks for the free quality content
Simply, thank you!
what an Explanation...........hats off ✌✌
Please add heap questions in SDE sheet.
It is necessary because no one teach us like you
Respect for Aditya verma increased after this lecture 🙇♀️🙇♀️
I thought Raj Bhaiya would break the record of his explanation, but he is still unbeatable.
Yes I can't agree more 😤😤🔥🔥
This person is gifted
very clear explanation, thanks
can we use max heap??
this was very hard for me . thanks for such a good explanation.
class Solution {
public:
vector maxSlidingWindow(vector&v, int k) {
vector ans;
int i,j;i=j=0;
deque q;
while((i < v.size()) && (ans.size() < v.size() - k + 1)){
while((j
Thank You very much! You explain very well.
had to watch 2 times to understand this but it was beautiful. thanks
Such an easy explanation, you make it look simple, love it!
Is there any algorithm related to next greatest element or next smallest element, like how to devise algorithms for these type of problems, how to know we need a deque in this case as we do operations on both sides here?
There's another solution of this using next greater element approach, saw it here th-cam.com/video/tCVOQX3lWeI/w-d-xo.html
as i was also thinking of applying nge algorithm.
Hello Striver, new here, can you tell whether you are covering only this SDE sheet here on any other topics too ? anyone ?
I am brining in series shortly..
The part that confuses me is dq.empty() or dq.front(), i thought they return a value at the index not the index itself. So how is it used here that it is checking the index and not the value? I am so confused.
the best explanation on yt.
I got this question in one interview round and also in the written round
dude!! your explanation is amazing.
I understood the solution!
I solved it using segment tree
directly jumped to solution,
Intution is missing... :(
Great Explanation
Genius guy🙌🙌
we can also do this using simple sliding window technique !?
Is the time complexity , really O(n) here ??.... because, if we take example, 6,4,5,3,2 with window size k =3, then once the greatest element 6 is removed, the next greatest element that is 5 should be placed at top, and for doing that worst case, there will be (k-1) comparisons. Anybody please correct me if I am wrong .
how is i-k the outbound element? at 16:02 ?
we can do this using queue also, why queue is not used and deque is used?
Nice explanation your videos are really good...please keep on making such videos...you are doing a great job.
Bro please make a video on your jee journey
why we should not directly give optimised solution of the particular problem in the interview
It can also be solved using Stack by finding Next Greater to Right:
vector maxSlidingWindow(vector& nums, int k) {
int n = nums.size();
stack stk;
stk.push(n-1);
vector ngr(n, 0);
ngr[n-1] = INT_MAX;
for (auto i=n-2; i>=0; i--){
while (! stk.empty() && nums[stk.top()]
I think you also have to add case when nge[j] == INT_MAX then break out of the while loop and set max element of that window as nums[j]
great explaination as always.... waiting for more videos
Thankyou So much for such excellent explaination
Ur explanation is so awesome.. It's really helpful to us..🙏
can you please upload the video of 862. Leetcode problem Shortest subarray with Sum at Least K.🙏🙏
please sir please I'm really stuck in this problem.
Thank You!!
Nice explanation bro!
Huge fan of your videos
Love❤😊
Understood! Amazing explanation as always, thank you very much!!
Why we push indices instead of actual elements?
to basically check if that value is within the window of size k
@@adeshsawant9937 That you can check from elements also right?
Can you give any test case where pushing elements will fail?
thanks for great explanation
Ur explanation is so awesome.. It's really helpful to us..🙏
can you plzz upload the video of 862. Leeetcode problem Shortest Subarray with Sum at Least K.🙏🙏
please sir please I'm really stuck in this prblm.
thank you striver!
it is not working for all the test cases in geeks for geeks
Thanks!
bhai tumhari video inti badiya hai to course laine ki jarurat hi nhi h
Bhaiya Tree series kb ari h ek br date bta do pls...
100k pe. Ye me 100 wi baar bol raha 😵💫😂
Thanks a lot! this was super helpful :)
3:20 - 6:25
14:22 ye time complexity O(n-k)+O(k) ni honi chahiye be because hum ans vector bhi to store kar rahe hai plz clear my doubt
awesome explanation bro.
all doubts gone
Great explanation!
Very good explanation, thank you bro