0
0
DSA Pythonprogramming~10 mins

Next Greater Element Using Stack in DSA Python - Execution Trace

Choose your learning style9 modes available
Concept Flow - Next Greater Element Using Stack
Start with empty stack
Pick next element from array
Is stack empty or top >= current element?
NoPop from stack and assign current as next greater
Repeat pop while condition holds
Push current element index to stack
Move to next element
Repeat until all elements processed
Assign -1 to remaining stack elements (no next greater)
End
We scan the array from left to right, using a stack to keep indexes of elements waiting for their next greater element. When a bigger element appears, we pop smaller ones and assign their next greater.
Execution Sample
DSA Python
arr = [4, 5, 2, 25]
stack = []
result = [-1]*len(arr)
for i in range(len(arr)):
    while stack and arr[stack[-1]] < arr[i]:
        result[stack.pop()] = arr[i]
    stack.append(i)
while stack:
    result[stack.pop()] = -1
print(result)  # [5, 25, 25, -1]
This code finds the next greater element for each item in the array using a stack to track indexes.
Execution Table
StepOperationCurrent Index (i)Stack (indexes)ActionResult ArrayVisual State
1Start-[]Initialize empty stack and result array [-1, -1, -1, -1][-1, -1, -1, -1]Stack: [] Result: [-1, -1, -1, -1]
2Process element0 (4)[]Stack empty, push index 0[-1, -1, -1, -1]Stack: [0] Result: [-1, -1, -1, -1]
3Process element1 (5)[0]arr[0]=4 < 5, pop 0, set result[0]=5; stack empty, push 1[5, -1, -1, -1]Stack: [1] Result: [5, -1, -1, -1]
4Process element2 (2)[1]arr[1]=5 > 2, push 2[5, -1, -1, -1]Stack: [1, 2] Result: [5, -1, -1, -1]
5Process element3 (25)[1, 2]arr[2]=2 < 25, pop 2, set result[2]=25; arr[1]=5 < 25, pop 1, set result[1]=25; stack empty, push 3[5, 25, 25, -1]Stack: [3] Result: [5, 25, 25, -1]
6End-[3]No more elements; pop remaining index 3, set result[3]=-1[5, 25, 25, -1]Stack: [] Result: [5, 25, 25, -1]
💡 All elements processed; remaining stack elements have no next greater, assigned -1
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4After Step 5After Step 6Final
stack[][0][1][1, 2][3][][]
result[-1, -1, -1, -1][-1, -1, -1, -1][5, -1, -1, -1][5, -1, -1, -1][5, 25, 25, -1][5, 25, 25, -1][5, 25, 25, -1]
i-0123--
Key Moments - 3 Insights
Why do we pop from the stack when the current element is greater than the element at the stack's top?
Because the current element is the next greater element for the popped index. This is shown in steps 3 and 5 where popping happens and result is updated.
Why do we push the current index onto the stack after popping smaller elements?
We push the current index because it might have a next greater element later. This is seen in steps 3, 4, and 5 where after popping, the current index is pushed.
Why do remaining elements in the stack get -1 in the result array at the end?
Because no greater element was found to their right. Step 6 shows assigning -1 to remaining indexes in the stack.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the content of the stack after processing element at index 2?
A[1, 2]
B[0, 2]
C[2]
D[1]
💡 Hint
Check the 'Stack (indexes)' column at Step 4 in the execution_table.
At which step does the result for index 1 get updated to 25?
AStep 3
BStep 4
CStep 5
DStep 6
💡 Hint
Look at the 'Result Array' column in execution_table rows where result changes for index 1.
If the array was [4, 3, 2, 1], what would be the final result array after processing?
A[3, 2, 1, -1]
B[-1, -1, -1, -1]
C[4, 4, 4, -1]
D[5, 5, 5, -1]
💡 Hint
Since no element has a greater element to its right, all remain -1 as per the exit_note.
Concept Snapshot
Next Greater Element Using Stack:
- Use a stack to store indexes of elements waiting for next greater.
- Iterate array left to right.
- While stack top element < current element, pop and assign current as next greater.
- Push current index to stack.
- After iteration, assign -1 to remaining stack indexes.
- Time: O(n), Space: O(n).
Full Transcript
This concept finds the next greater element for each item in an array using a stack. We start with an empty stack and a result array filled with -1. We scan the array from left to right. For each element, we pop from the stack all indexes whose elements are smaller than the current element and assign the current element as their next greater. Then we push the current index onto the stack. After processing all elements, any indexes left in the stack have no next greater element, so their result remains -1. This method efficiently finds next greater elements in one pass.