L6. Next Greater Element - II | Stack and Queue Playlist

Поділитися
Вставка
  • Опубліковано 22 гру 2024

КОМЕНТАРІ • 76

  • @Demon01Editz
    @Demon01Editz 5 місяців тому +8

    we can do it with below code also it is using same concept but we will simply start with max element in array (because we know that its NGE will be -1 and we know that if we don't find any other element who is greater than our current element then we know maxelement will be our answer) then we will traverse through other elements like NGE-I video(because we know the ending)
    class Solution {
    public:
    vector nextGreaterElements(vector& nums) {

    int maxele = INT_MIN;
    int maxidx = -1;
    int n = nums.size();
    for(int i=0;i(maxidx-n-1);i--){

    int idx = i;
    if(idx nums[idx]){
    nge[idx] = st.top();
    st.push(nums[idx]);
    }
    else{

    while(!st.empty() && st.top()

  • @onelove177
    @onelove177 5 місяців тому +11

    Literally I have at least 10 videos to get this but I didn't get! But sir Striver!😍 Thank you!

  • @Kshitijsingh-n7f
    @Kshitijsingh-n7f 3 місяці тому +5

    MY APPROACH-->
    approach-1(optimal)
    TC-O(3N)
    SC-O(2N) [including memory for storing returning answer]
    //push all ele from n-2 to start then traverse from the n-1 to the start in similar way as NGE 1 problem
    since in NGE 1 problem we didnt have any greater ele for the last so we started from last and just check next left and left updating the their maxes but here since last ele can also have the NGE so we have put all elements that can be NGE of last ele then we do like normal NGE 1 problem solution
    vector nextGreaterElements(vector& nums) {
    stacks;
    int n=nums.size();
    vectorv(n);
    for(int i=n-2;i>=0;i--){
    s.push(nums[i]);
    }
    for(int i=n-1;i>=0;i--){
    while(!s.empty() && s.top()

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

      thats what I did too

    • @aruna5869
      @aruna5869 11 днів тому

      This too taking TC O(4n) bro!!
      In worst case, That while takes tottally pop() atmost 2n elements from the stack

  • @SomrikTapaswi
    @SomrikTapaswi 4 місяці тому +2

    loved the way you made us understand !

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

    we can put the all the elements in order expect the last element to get compared then perform the operation using the NGE (using the stack)here the time complexity at worst case becomes like 0(2n+1) and space complexity also 0(n+2).

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

    @Take you forward
    Small optimisation :-
    Why we even need to push 2n elements push only till (i < n)
    Then we would not waste extra time in pushing and popping...

  • @iamnoob7593
    @iamnoob7593 14 днів тому

    Brilliant explanation . Thanks striver

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

    The better solution was the goto hint to approach the optimal approach. Striver OP 🔥

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

    Very clear explanation! Thanks a lot!

  • @rahuldwivedi4758
    @rahuldwivedi4758 18 днів тому +1

    14:43 why would the space complexity be 0(2N)? Shouldn't it be O(N) as only those many elements that are in the array can be in stack at a given point?

    • @CR-qg6ku
      @CR-qg6ku 17 днів тому

      I was also thinking the same

    • @Ununtag
      @Ununtag 15 днів тому

      yeah, i think even the time complexity should be about O(3N) and not 4N

  • @crazybro4383
    @crazybro4383 26 днів тому

    Tried question for 15 minutes, not able to solve so I thought soln dekh leta hu starting ke question dekhne padte hai to understand how the approaches work for a particular data structure.............aapki vid kholi you didn't even explained the question, at time stamp 1:00 I paused the vid and solved the question myself, felt good........abse roz dsa grind hoga 3rd sem aa gya thodi fatri hai for placements and internship vaise hi tier3 clg h

  • @parth2439
    @parth2439 29 днів тому

    understood, Thank you striver !

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

    Thank You So Much Sir
    for this Amazing Lecture

  • @aravatanish3170
    @aravatanish3170 3 місяці тому +5

    Striver please upload Heap series

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

    Excellent explanation!

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

    Thank you for excellent explaination.

  • @closer9689
    @closer9689 4 місяці тому +1

    CODE =>
    class Solution {
    public:
    //Better Approach :-> without making extra circular array
    vector nextGreaterElements(vector& nums) {

    int n = nums.size();
    stack st;
    for(int i = n-2 ; i >= 0; --i)
    {
    st.push(nums[i]);
    }
    vector result;
    for(int i = n-1 ; i>= 0 ; --i)
    {
    int curr = nums[i];
    while ( !st.empty() && st.top()

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

    Awesome explaination

  • @Akash-Bisariya
    @Akash-Bisariya 3 місяці тому

    very nicely explained 😍😍

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

    Excellent video

  • @shubhamlifearts8138
    @shubhamlifearts8138 5 місяців тому

    Thanks bhaiya for great content ❤

  • @alessandrocamilleri1239
    @alessandrocamilleri1239 4 місяці тому +2

    Thank you and great explanation. Can't you just traverse the array circularly in reverse from the max element index? That way you would just add an O(n) to the original TC of NGE1. I coded it as follows:
    vector nextGreaterElements(vector& nums)
    {
    int n = nums.size();
    int maxIndex = 0;
    for (int i = 1; i < n; i++) // ADDITIONAL O(n)
    if (nums[i] > nums[maxIndex]) maxIndex = i;

    stack st;
    vector nge(n);
    for (int i = maxIndex; i > maxIndex - n; i--)
    {
    int j = (n + i) % n;
    while (!st.empty() && st.top()

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

    Smart solution. Wow.

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

    Thankyou bhaiya!!

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

    excellent explanation

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

    Isn't the space complexity O(n)? Say the stack contains some element a, after which there are some elements and then a is pushed into stack again. When that occurs all elements from top to a will be popped. So there can never be more than n elements in the stack, is what I think. Please correct me if I'm making a mistake.

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

      Same thoughts!

  • @karthi2174
    @karthi2174 17 днів тому

    Hello everyone, my placements are starting in March 2025. I have started learning DSA using the TakeUforward SDE sheet and have completed the first 10 problems. However, I was able to understand only 3 of them, and I am struggling to build logic on my own. I am unsure if I am on the right track or where to start. Could you please give me some advice on how to approach solving problems independently and where I should begin? I have programming knowledge but need guidance. I am not aiming to join a big MNC company, but I want to prepare effectively.

  • @tusharsingh1257
    @tusharsingh1257 5 місяців тому

    Completed 19th July

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

    class Solution {
    public int[] nextGreaterElements(int[] nums) {
    int n = nums.length;
    int[] nge = new int[n];
    Stack stack = new Stack();
    for(int i=2*n-1; i>=0; i--) {
    int index = i%n;
    while(!stack.isEmpty() && nums[index] >= stack.peek()) stack.pop();
    if(stack.empty()) nge[index] = -1;
    else nge[index] = stack.peek();
    stack.push(nums[index]);
    }
    return nge;
    }
    }

  • @SibiRanganathL
    @SibiRanganathL 4 місяці тому +1

    Understood

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

    ⭐⭐Solution in Python:
    Can Also be Sovled Like This:
    class Solution:
    def nextGreaterElements(self, nums: List[int]) -> List[int]:

    stack = []
    n = len(nums)
    res = [-1] * n
    for i in range(2*n):
    index = i%n # Here the Cur is the Index , NOT the current Value.
    while stack and nums[index] > nums[stack[-1]]:
    res[stack[-1]] = nums[index]
    stack.pop()
    stack.append(index)
    return res

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

    My approach:
    class Solution {
    private:
    void findNgeForLastEle(vector &nums,int n,stack &st,vector &res){
    // int nge = -1;
    for(int i=n-2;i>=0;i--){
    if(nums[i]>nums[n-1])
    st.push(nums[i]);
    }
    if(!st.empty()) res[n-1] = st.top();
    st.push(nums[n-1]);
    }
    public:
    vector nextGreaterElements(vector& nums) {
    stack st;
    int n = nums.size();
    vector res(n,-1);
    findNgeForLastEle(nums,n,st,res);
    for(int i = n-2;i>=0;i--){
    while(!st.empty() && st.top()

  • @abhaykumarsingh3884
    @abhaykumarsingh3884 4 місяці тому +11

    Steps
    1. Just put all element from end in stack first.
    2. Now perform same operations as you have performed in Next-Greater Element-I
    You don't need to think about hypothical array

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

      I also thought of the same method

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

      great method

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

      what is thought process behind it intiutiton can u please explain me brother

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

      great observation!

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

    Implement Queue using Stacks put this one also! thnku

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

    thanks bhai

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

    UNDERSTOOD;

  • @KartikeyTT
    @KartikeyTT 5 місяців тому

    tysm sir

  • @shreyxnsh.14
    @shreyxnsh.14 5 місяців тому

    C++ Code:
    class Solution {
    public:
    vector nextGreaterElements(vector& nums) {
    stack st;
    int n = nums.size();
    vector ans(n, -1);
    for(int i=2*n-1;i>=0;--i){
    while(!st.empty() && st.top()

    • @omkarshendge5438
      @omkarshendge5438 5 місяців тому

      you need to reverse the ans array too

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

      @@omkarshendge5438 take vector ans (n,-1) it will be reversed

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

      @@omkarshendge5438 yes you are right

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

    guys jo for the first time stacks and queues kr raha h, kya tumse ye questions khud se ho paate hn ?
    Please batana!! kyuki mujhse literally nhi hopaate!! hn, ek aad baar meri approach jrur same hojaati h striver bhaiya jesi

    • @ashwani6527
      @ashwani6527 3 місяці тому +4

      For beginners the best way is to watch and learn then understand then revise

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

      @@ashwani6527 ok bhaiya!!

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

      kisi se nhi hote jab tak us type ke question na kiye ho

  • @omkarshendge5438
    @omkarshendge5438 5 місяців тому +2

    you forgot to reverse the ans vector by the way, like that is how i got all cases passed.

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

      Nah not needed 😊

    • @ashu_10011
      @ashu_10011 5 місяців тому

      that is needed only when you are using push_back or emplace_back functions to add elements in the answer vector

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

      @@ashu_10011 what's the alternate method to add to the vector array?

  • @AradhyaVerma-p3m
    @AradhyaVerma-p3m Місяць тому

    BRUTEFORCE: ***JAVA***
    class Solution {
    public int findGreater(int index,int value,int []nums){
    for(int i=index;i

  • @vinit_notfound
    @vinit_notfound 5 місяців тому

    ❤❤❤❤

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

    public static void findNextGreater(int[] inputArray, int[] output){
    Stack stack = new Stack();
    //Iterate the input Array
    for (int index=inputArray.length -1 ;index>=0;index--){
    //pop the highest elements
    while(!stack.isEmpty() && inputArray[index] > stack.peek()) stack.pop();
    //stack empty case
    if (stack.isEmpty()) {
    stack.push(inputArray[index]);
    output[index] = -1;
    }
    // else we found the next greater element just push to stack and output array
    else{
    output[index] = stack.peek();
    stack.push(inputArray[index]);
    }
    }
    }
    i think these one worked for me, which is simple, no need of double iteration, if i am wrong please correct me, Thanks !!!

  • @crazybro4383
    @crazybro4383 25 днів тому

    I impleted a better approach than raj bhaiya with TC= O(3n) myself-
    class Solution {
    public:
    vector nextGreaterElements(vector& nums) {
    stack st;
    queue q;
    int n = nums.size();
    vector ans(n);
    for(int i=0; i=0; i--){
    while(!st.empty() && nums[i]>= st.top()){
    st.pop();
    }
    if(st.empty()){
    st.push(nums[i]);
    while(!q.empty() && nums[i]>=q.front()){
    q.pop();
    }
    if(q.empty()){
    ans[i] = -1;
    }
    else{
    ans[i] = q.front();
    }
    }
    else{
    ans[i] = st.top();
    st.push(nums[i]);
    }
    }
    return ans;
    }
    };

  • @amankumarsingh3995
    @amankumarsingh3995 5 місяців тому

  • @LordSarcasticVlogger
    @LordSarcasticVlogger 7 днів тому

    VERY HARD TO UNDERSTAND

  • @LordSarcasticVlogger
    @LordSarcasticVlogger 7 днів тому

    KUCH SAMAJH NAHI AAYA

  • @IshraqTanvir
    @IshraqTanvir 3 місяці тому +6

    his explanaition is too well.........................................................................but, it would be better if he don't write pseudocode and write real code

    • @sohaildarwajkar9979
      @sohaildarwajkar9979 3 місяці тому +6

      Then u would complain about the language in which he is writing the code..Grow Up man!!

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

      @@sohaildarwajkar9979 actually I won't ....... ...... cause most of the cpp mans whether like java or c++.......both the language is much closer syntaxically......

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

      If you know the logic and pseudo code, its too easy to write code. Its all about syntax then.

  • @LordSarcasticVlogger
    @LordSarcasticVlogger 7 днів тому +1

    abe bhai...bina logic ke code kr rha h...code rataa hua h tereko

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

    Understood

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

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

    Understood

  • @abhinavabhi3568
    @abhinavabhi3568 12 днів тому

    Understood