SarthakKeshari / CPP-Questions-and-Solutions

This repository aims to solve and create new problems from different spheres of coding. A path to help students to get access to solutions and discuss their doubts.
MIT License
47 stars 132 forks source link

Create Next_Greater_Element.cpp #356

Closed Master-Helix closed 2 years ago

Master-Helix commented 2 years ago

Issue Id you have worked upon - #346

Briefly explain your program logic -

-> Last element of array has no rightmost element , so output is -1.
-> Push that element in stack.
-> Traverse the array from right to left (from second last element to leftmost), and check the following.
-> If the current element is smaller than recent top of stack, then that top is next Greater element of that current element, so push the stack top in output vector.
-> Else, check while stack is not empty and stack top is less than the current value, Pop the items from stack.
-> If stack gets empty, that means no NGE of current element exists, so push -1 in output vector.
-> If we found a NGE, then push that top of stack into output vector.
-> Finally, push the current element of array in stack.
-> Since the output vector has elements from right to left order, so reverse the vector and return it.

Screenshots(Attach 2 screenshots of your own input and output) -

1

2


Problem Link - https://practice.geeksforgeeks.org/problems/next-larger-element-1587115620/1


Checklist:

Eg - If your code follow the below guidelines. Kindly change [] to [x]

All the conditions should be fulfilled for considering your code for merging -

SarthakKeshari commented 2 years ago

@Master-Helix, I Appreciate the code presentation, organization and commenting Appreciating by Leveling up your question from level2 to level3

Master-Helix commented 2 years ago

Thanks @SarthakKeshari .