Sliding Window Maximum | Leetcode

Поділитися
Вставка
  • Опубліковано 2 жов 2024
  • Check our Website:
    In case you are thinking to buy courses, please check below:
    Link to get 20% additional Discount at Coding Ninjas: bit.ly/3wE5aHx
    Code "takeuforward" for 15% off at GFG: practice.geeks...
    Code "takeuforward" for 20% off on sys-design: get.interviewr...?_aff=takeuforward
    Crypto, I use the Wazirx app: wazirx.com/inv...
    Take 750 rs free Amazon Stock from me: indmoney.oneli...
    Earn 100 rs by making a Grow Account for investing: app.groww.in/v...
    Linkedin/Instagram/Telegram: linktr.ee/take...
    ---------------------------------------------------------------------------------------------------------------------------------------------------- SDE sheet: bit.ly/takeUfor...
    Watch at 1.25x for better experience ..
    ✅Use coupon-code "TAKEUFORWARD" for getting 15% for all CN courses: aff.codingninj...
    ---------------------------------------------------------------------------------------------------------------------------
    Problem Link: leetcode.com/p...
    C++/Java Code: takeuforward.o...
    ---------------------------------------------------------------------------------------------------------------------------
    ✅Use coupon-code "STRIVER" for getting 10% on all subscriptions of Unacademy
    ✅Use coupon-code "TAKEUFORWARD" for getting 10% for all GFG courses: bit.ly/tuf_gfgC...
    ✅Please Please SUBSKRIIIBEEEEE the new channel: / @striver_79
    ---------------------------------------------------------------------------------------------------------------------------
    Products that I use:
    Best Mic in Affordable Range: amzn.to/3hiTr9p
    Yeti mic: amzn.to/3dL4tDF
    Boya mic: amzn.to/3h4ROgy
    Logitech webcam: amzn.to/3h7d2KI
    Cooling pad: amzn.to/3y46pi4
    Wacom pad: amzn.to/3xacSIq
    Ring light: amzn.to/3y7aaU1
    Mic Arm Stand: amzn.to/3qzMuFa
    Digitek Green light stand: amzn.to/2U7B3bI
    Digitek Stand: amzn.to/363m7Oo
    Tripod: amzn.to/35ZmbyT
    Office chair: amzn.to/3qysu5Z
    Ipad Air: amzn.to/3hjpiXx
    Iphone 12: amzn.to/3AavyJV
    Watch: amzn.to/3hn7w5A
    Macbook Air: amzn.to/363lSTu
    Macbook Pro: amzn.to/3qCczDr
    Board: amzn.to/3x8GLIO
    Mouse: amzn.to/360Asv1
    ---------------------------------------------------------------------------------------------------------------------------
    ✅Placement Series: • Let's give back to the...
    ✅Placement Series (Arrays, Sorting..): • C++ and Java |Brute-Be...
    ✅Hashing Playlist: • Two Sum Problem | Leet...
    ✅Greedy Playlist: • N meetings In One Room...
    ✅Recursion Playlist: • L8. Combination Sum | ...
    ✅Graph Playlist: • 3 MAJOR ANNOUNCEMENTS ...
    ✅Two Pointer Playlist: • 3 SUM | Brute | Better...
    ✅Binary Search Playlist: • Nth Root of a Number U...
    ✅LinkedList Playlist: • Reverse a Linked List ...
    ✅Advanced DS playlist: • Fenwick Tree Tutorial ...
    ✅Stack&Queue Playlist: • Implementation of Stac...
    ✅Greedy Algorithms: • N meetings In One Room...
    ---------------------------------------------------------------------------------------------------------------------------
    If you appreciate the channel's work, you can join the family: bit.ly/joinFam...
    ✅Thumbnail Creator: / rikonakhuli
    ✅ Striver's Linkedin Profile: / ​
    ✅ Instagram: / ​
    ✅Connect with us: www.google.com... (Use Link in Mobile only, if not works search "takeUforward" in telegram)..
    ##dsa​ #striver #leetcode

КОМЕНТАРІ • 221

  • @takeUforward
    @takeUforward  3 роки тому +135

    If you understand it, please do like it, and if possible please spare 2 seconds for a comment :)

    • @anoopraj9319
      @anoopraj9319 3 роки тому

      make videos on dp please

    • @JohnWick-kh7ow
      @JohnWick-kh7ow 3 роки тому

      What's the difference between deque and list?

    • @PrinceKumar-el7ob
      @PrinceKumar-el7ob 2 роки тому +5

      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.

    • @pranayjain._
      @pranayjain._ Рік тому

      @@PrinceKumar-el7ob It would work. Try some test cases.

    • @artofwrick
      @artofwrick 8 місяців тому

      The best explanation on sliding window

  • @zetro6311
    @zetro6311 2 роки тому +96

    I got this question in a Microsoft interview for SDE 1

    • @kingmaker9082
      @kingmaker9082 2 роки тому

      Is it offcampus or oncampus

    • @zetro6311
      @zetro6311 2 роки тому

      @@kingmaker9082 Off campus

    • @kingmaker9082
      @kingmaker9082 2 роки тому +1

      @@zetro6311 from where u applied for Microsoft or have u got any referral? Plz guide me...btw what is the result of interview bro?

    • @vinyass3733
      @vinyass3733 Рік тому

      @@kingmaker9082 hello bro? which batch are you?

    • @kingmaker9082
      @kingmaker9082 Рік тому

      @@vinyass3733 23 batch

  • @priyanshityagi8313
    @priyanshityagi8313 2 роки тому +80

    This explanation literally made me overcome my fear of stacks and queues. Thank you so much!

    • @ayushrawat7951
      @ayushrawat7951 2 роки тому

      Ya exactly..... I also have fear of stack and queue.. Even though they are quite easy to understand.

    • @purushottam108
      @purushottam108 3 місяці тому

      How one question can over come your fear? 🤔🤔🤔🤔

  • @shashank_0807
    @shashank_0807 Місяць тому +2

    Much better explanation than in the new playlist !

  • @patelchintu6492
    @patelchintu6492 3 роки тому +34

    Waiting for tree series :)

  • @thatbadguy2899
    @thatbadguy2899 3 роки тому +25

    Please increase the frequency of uploads as this is PLACEMENT SEASON

  • @raghav5354
    @raghav5354 Рік тому +5

    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.

  • @parthsalat
    @parthsalat Рік тому +10

    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!

  • @vuyyurishanmukhaabhinavvar4096
    @vuyyurishanmukhaabhinavvar4096 3 роки тому +5

    Bhai when your course starts in unacademy pls update waiting for your course

  • @earninghere7442
    @earninghere7442 3 місяці тому +1

    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)

  • @harshexploring4922
    @harshexploring4922 2 роки тому +12

    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

    • @coolmishrag8622
      @coolmishrag8622 6 місяців тому +2

      bro getting harsh with apna collegeg

  • @aryanchauhan8897
    @aryanchauhan8897 3 роки тому +8

    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.

  • @deepikasrivastava3040
    @deepikasrivastava3040 2 роки тому +4

    Best Explanation. Thank you so much. Finally understood the use of deque for this problem.

  • @naveengarg7435
    @naveengarg7435 2 роки тому +2

    directly jumped to solution,
    Intution is missing... :(

  • @Code__madad
    @Code__madad Рік тому +1

    it is not working for all the test cases in geeks for geeks

  • @rishurana9655
    @rishurana9655 2 роки тому +2

    This question can also be solve using heap

  • @pb_yt992
    @pb_yt992 3 роки тому +5

    Such a Nice Explanation even a beginner can understand. Thanks a lot

  • @aadityaupadhyay6264
    @aadityaupadhyay6264 3 роки тому +3

    That definitely not at 5:15 reminds me of Dhoni xD.

  • @neerajgarg9096
    @neerajgarg9096 2 роки тому +2

    *Brute force*
    class Solution {
    public:
    vector maxSlidingWindow(vector& nums, int k) {
    vectorans;
    int n = nums.size();
    for(int i=0; i

  • @koushalsharma7041
    @koushalsharma7041 2 роки тому +6

    It is always challenging as well as fun to learn the optimal solution. But, your explanation helps a lot to understand it better.

  • @vedanshbhardwaj6548
    @vedanshbhardwaj6548 3 роки тому +4

    Hello Striver, new here, can you tell whether you are covering only this SDE sheet here on any other topics too ? anyone ?

    • @takeUforward
      @takeUforward  3 роки тому +6

      I am brining in series shortly..

  • @charanrc9729
    @charanrc9729 Рік тому +1

    Can u pls provide me a python soln for it

  • @sushantchoudhary444
    @sushantchoudhary444 Рік тому +1

    you are amazing God bless you. I wanna become like you one day

  • @rishabhyadav4994
    @rishabhyadav4994 3 роки тому +3

    This can also be solved using multiset, can we use multiset in the interview bhaiya?

  • @Satya-g5t
    @Satya-g5t 29 днів тому +1

    good explanation, thank you.

  • @stith_pragya
    @stith_pragya 5 місяців тому +1

    UNDERSTOOD..........Thank You So Much for this wonderful video...........🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻

  • @rohandevaki4349
    @rohandevaki4349 2 роки тому +2

    how is i-k the outbound element? at 16:02 ?

  • @parthh1112
    @parthh1112 7 місяців тому

    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

  • @aryanchauhan8066
    @aryanchauhan8066 3 роки тому +3

    Very good explaination , though i have to see it 2 times to completely understand the concept👍

  • @nayan_CSE
    @nayan_CSE Рік тому +1

    What a explanation 😯...I think this is the best video of window problem in UA-cam... Thank you so much for this great video....

  • @khumukchamsonam4471
    @khumukchamsonam4471 3 роки тому +3

    great explaination as always.... waiting for more videos

  • @rishabhkumar8115
    @rishabhkumar8115 3 роки тому +4

    can someone please explain to me line 13, why he put if(i >= k - 1) when I will reach 2 in case of k = 3, then for I =4, 5, 6 to will continuously putting element into ans.
    Please solve my doubt if someone can.

    • @rohandeshmukh3989
      @rohandeshmukh3989 3 роки тому +4

      yeah bcz there will be n-k-1 subarrays so if you just dry run it ,it will start putting the max into the ans vector after the first sub array has traversed,and then after at each i it will store the max value for next respective sub array

    • @dipanshupandey7952
      @dipanshupandey7952 2 роки тому

      so that it can reach the length of subarray

  • @pawanharwani4598
    @pawanharwani4598 Місяць тому +1

    Why we push indices instead of actual elements?

    • @adeshsawant9937
      @adeshsawant9937 Місяць тому

      to basically check if that value is within the window of size k

    • @pawanharwani4598
      @pawanharwani4598 Місяць тому

      @@adeshsawant9937 That you can check from elements also right?
      Can you give any test case where pushing elements will fail?

  • @its_kundan
    @its_kundan 9 місяців тому

    I tried this question but 40/50 testcase passed, I am here to see whats the mistake I have done
    ```
    class Solution {
    public:
    vector maxSlidingWindow(vector& nums, int k) {
    int n = nums.size();
    int i=0,j=0;
    vector ans;
    priority_queue pq;
    if(k>n){
    ans.push_back(*max_element(nums.begin(),nums.end()));
    return ans;
    }
    while(j

  • @shubham7668
    @shubham7668 2 роки тому +18

    Respect for Aditya verma increased after this lecture 🙇‍♀️🙇‍♀️
    I thought Raj Bhaiya would break the record of his explanation, but he is still unbeatable.

  • @abhishekkmandal
    @abhishekkmandal 3 роки тому +9

    at 3:48 , deque should be Double ended queues I guess and not doubly linked list , btw nice explanation :)

    • @alokesh985
      @alokesh985 3 роки тому +3

      I think he meant that double-ended queues are typically implemented using doubly linked lists

    • @harshexploring4922
      @harshexploring4922 2 роки тому

      @@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

  • @AbhishekKumar-hh8xc
    @AbhishekKumar-hh8xc 2 роки тому +2

    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

  • @abhityagi9807
    @abhityagi9807 Рік тому

    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

  • @perumallayaswanth83
    @perumallayaswanth83 3 роки тому +1

    Bro can u please make a video on how to deal with large numbers and what exactly 10^9+7.

  • @lifegood6401
    @lifegood6401 3 роки тому +11

    Waiting for tree series eagerly.
    Placement already started in college, and tree , dp, strings remaining from the sheet

  • @prajunathunt
    @prajunathunt 2 роки тому +1

    A day before the interview at 2x speed.

  • @AyushGupta-kp9xf
    @AyushGupta-kp9xf 2 роки тому +2

    Thanks man I was doubtful about the On complexity. your explanation cleared it :)

  • @StudyEmail-p9u
    @StudyEmail-p9u 8 місяців тому +1

    Thank You!!

  • @freshcontent3729
    @freshcontent3729 3 роки тому +1

    bhaiya please bring more videos fast fast .. placements are starting!!

  • @iamnoob7593
    @iamnoob7593 Рік тому

    Understood Thanks Striver , I am suffering from health issues , Still not giving up.

  • @subhankarkanrar9494
    @subhankarkanrar9494 2 місяці тому +1

    Love❤😊

  • @shalabhbhatiya2292
    @shalabhbhatiya2292 3 роки тому +1

    bhai tumhari video inti badiya hai to course laine ki jarurat hi nhi h

  • @spardha-yug
    @spardha-yug 2 роки тому +1

    THank you bro.
    Brute force+Optimized+code explanation---->complete video.
    Thanks a ton.

  • @scorcism.
    @scorcism. Рік тому

    we can also do this using simple sliding window technique !?

  • @timacorn2536
    @timacorn2536 11 місяців тому

    Wtf is this approach, sometimes you insert at the front, sometimes at the back, sometimes you pop, other times you say decreasing order then forget it, what the hell

    • @artofwrick
      @artofwrick 8 місяців тому

      We insert only at the back. That is the way it is done with it. We only remove it once in the front (when the limit of k exceeds) and once from back (when we encounter a greater element because we aren't forgetting the decreasing order)

  • @asp1859
    @asp1859 11 місяців тому

    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 .

  • @srijannallamothu795
    @srijannallamothu795 3 місяці тому

    Time complexity for brute force sol is wrong

  • @biswaranjanbarik4052
    @biswaranjanbarik4052 2 роки тому

    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.

  • @artofwrick
    @artofwrick 8 місяців тому

    The java code: ☕🌞
    package subset;
    import java.util.*;
    public class maxSlidingWindow {

    public static int[] maxSlide(int[] nums, int k) {
    int[] ans=new int[nums.length-k+1];
    int index=0;
    Deque q=new LinkedList();
    for(int i=0;i

  • @1qwertyuiop1000
    @1qwertyuiop1000 Рік тому

    How about using Max Heap with size K.. time complexity will be NLogN i guess.. Space complexity will be O(K)

  • @rishabhbatra3022
    @rishabhbatra3022 3 роки тому +2

    Bhaiya Tree series kb ari h ek br date bta do pls...

    • @takeUforward
      @takeUforward  3 роки тому +3

      100k pe. Ye me 100 wi baar bol raha 😵‍💫😂

  • @1murkeybadmayn
    @1murkeybadmayn 11 місяців тому

    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.

  • @GeniuslyTensai
    @GeniuslyTensai 2 роки тому

    Can someone explain why is this code giving me wrong answer after submitting on leetcode?
    class Solution {
    public:
    vector maxSlidingWindow(vector& nums, int k) {
    vector ans;
    int n = nums.size();
    int i=0, j=0;
    priority_queue q;
    if(k > n){
    ans.push_back(*max_element(nums.begin(), nums.end()));
    }
    while(j < n){
    q.push(nums[j]);
    if(j-i+1 < k) j++;
    else if(j-i+1 >= k){
    int top = q.top();
    ans.push_back(top);
    if(nums[i] == top) q.pop();
    i++;
    j++;
    }
    }
    return ans;
    }
    };

  • @HarshKumar-nv1fo
    @HarshKumar-nv1fo 3 роки тому

    New roast video out 🔥🔥
    #BEINGFUNNYCASM
    BEING FUNNYCASM yt channel

  • @511sanjeevthalod7
    @511sanjeevthalod7 3 роки тому +1

    Bro please make a video on your jee journey

  • @poorvaparande5933
    @poorvaparande5933 2 роки тому +1

    Thanks a lot! this was super helpful :)

  • @jayantgahlot2653
    @jayantgahlot2653 Рік тому

    we can't use equal to it will give wrong answer

  • @rohankumar393
    @rohankumar393 3 роки тому +1

    Please add heap questions in SDE sheet.

  • @SayaliRahane
    @SayaliRahane 2 місяці тому

    can someone please explain me last if statement ??

  • @vaalarivan_p
    @vaalarivan_p Рік тому +1

    3:20 - 6:25

  • @juanceja899
    @juanceja899 2 роки тому

    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.

  • @manask8116
    @manask8116 11 місяців тому

    you can do by using a multiset as well , it takes nlogn but its very simple to write the code

  • @alimjafargaming6925
    @alimjafargaming6925 3 роки тому +1

    great explanation bhai

  • @Luk3Stein
    @Luk3Stein Рік тому

    Godly explanation. Suddenly, this problem does not look Leetcode Hard level

  • @jaydalsaniya6986
    @jaydalsaniya6986 2 роки тому

    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 .

  • @kidvschild7240
    @kidvschild7240 2 роки тому +1

    Great brother 👌👌 keep it up 👆

  • @biswaranjanbarik4052
    @biswaranjanbarik4052 2 роки тому

    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.

  • @shristisrivastava7054
    @shristisrivastava7054 10 місяців тому

    Huge fan of your videos

  • @sapnilpatel1645
    @sapnilpatel1645 2 роки тому

    here why we don't calculate the space complexity of the vector? Anyone?

  • @kshitijmishra2716
    @kshitijmishra2716 2 роки тому

    why we should not directly give optimised solution of the particular problem in the interview

  • @gandhijainamgunvantkumar6783
    @gandhijainamgunvantkumar6783 2 роки тому

    Bhaiya please make a video on the question: Find maximum of minimum for all the window sizes.

  • @Benstokes555
    @Benstokes555 4 місяці тому

    bro has unreal grudge on python

  • @KittyInCali
    @KittyInCali Місяць тому

    thanks for great explanation

  • @devankdubey6657
    @devankdubey6657 2 роки тому

    can u explain last line r[ri++]=a[q.peek()];@19:29

  • @sahilsingh5695
    @sahilsingh5695 Рік тому

    not able to understand the lst part of the i>-=k-1 onwards part

  • @itz_me_imraan02
    @itz_me_imraan02 Рік тому

    I solved it using segment tree

  • @arunimadas3183
    @arunimadas3183 Рік тому

    how is the r[] size = int [n-k+1] can anyone explain?

  • @kapilpatel9379
    @kapilpatel9379 Рік тому

    Could not understand completely, but will come back

  • @nani4027
    @nani4027 3 роки тому +1

    Nice explanation bro!

  • @Emperor854
    @Emperor854 Рік тому

    Thx a lot brother

  • @mohammedraqeeb4392
    @mohammedraqeeb4392 2 роки тому +1

    thank you bhaiya

  • @_-6912
    @_-6912 3 роки тому +1

    I understood the solution!

  • @rajeshg3570
    @rajeshg3570 2 роки тому +1

    Can't find a better explanation than this for a hard problem.. simple love it

  • @yeswanthh5068
    @yeswanthh5068 2 роки тому +1

    Understood sir

  • @herculean6748
    @herculean6748 Рік тому

    we can do this using queue also, why queue is not used and deque is used?

  • @shobhitmishra739
    @shobhitmishra739 3 роки тому +1

    can we use max heap??

  • @digvijaypatil2147
    @digvijaypatil2147 Рік тому

    better than apna college

  • @helderfilho4724
    @helderfilho4724 Рік тому

    Thank You very much! You explain very well.

  • @sudiksha586
    @sudiksha586 Рік тому

    thank you striver!

  • @rushikeshdeshmukhmarathibo7465

    Understood bhaiya ❤

  • @AlokKumar-or8jz
    @AlokKumar-or8jz Рік тому +2

    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;


    }

  • @amansamal8233
    @amansamal8233 2 роки тому +1

    understoooddddddd🥺❤

  • @biswaranjanbarik4052
    @biswaranjanbarik4052 2 роки тому

    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.

  • @saketmehta6697
    @saketmehta6697 Рік тому

    still i-k is confusing?

  • @siddheshb.kukade4685
    @siddheshb.kukade4685 2 роки тому

    Question Link : leetcode.com/problems/sliding-window-maximum/