Bird
Raised Fist0
DSA Cprogramming~10 mins

Next Greater Element Using Stack in DSA C - Execution Trace

Choose your learning style10 modes available
Concept Flow - Next Greater Element Using Stack
Start with empty stack
↓
Iterate over array from right to left
↓
While stack not empty and top <= current element
↓
Pop stack
↓
If stack empty -> No greater element, assign -1
↓
Else top of stack is next greater element
↓
Push current element onto stack
↓
Move to next element left
↓
Repeat until all elements processed
↓
Result array filled with next greater elements
We scan the array from right to left, using a stack to keep track of candidates for the next greater element. For each element, we pop smaller or equal elements from the stack until we find a greater one or the stack is empty.
Execution Sample
DSA C
int arr[] = {4, 5, 2, 25};
int n = 4;
int result[4];
// Compute next greater elements
This code finds the next greater element for each item in the array using a stack.
Execution Table
StepOperationCurrent ElementStack BeforeStack AfterNext Greater Element AssignedResult Array State
1Start-[][]-[-, -, -, -]
2Process element 25 (rightmost)25[][25]-1[-, -, -, -1]
3Process element 22[25][25, 2]25[-, -, 25, -1]
4Process element 55[25, 2][25, 5]25[-, 25, 25, -1]
5Process element 44[25, 5][25, 5, 4]5[5, 25, 25, -1]
6End-[25, 5, 4][25, 5, 4]-[5, 25, 25, -1]
💡 All elements processed, result array contains next greater elements or -1 if none.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4After Step 5Final
Stack[][25][25, 2][25, 5][25, 5, 4][25, 5, 4]
Current Element-25254-
Result Array[-, -, -, -][-, -, -, -1][-, -, 25, -1][-, 25, 25, -1][5, 25, 25, -1][5, 25, 25, -1]
Key Moments - 3 Insights
Why do we pop elements from the stack when they are smaller or equal to the current element?
Because those smaller or equal elements cannot be the next greater element for the current or any earlier elements. This is shown in step 4 where 2 is popped before pushing 5.
Why do we start scanning the array from right to left?
Because the next greater element for the rightmost element is always -1 (no elements to the right). Scanning from right to left allows us to use the stack to find the next greater element efficiently, as seen in step 2.
What does it mean when the stack is empty while processing an element?
It means there is no greater element to the right of the current element, so we assign -1 as the next greater element, as in step 2 for element 25.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the next greater element assigned for element 4 at step 5?
A5
B25
C-1
D4
💡 Hint
Check the 'Next Greater Element Assigned' column at step 5 in the execution table.
At which step does the stack first contain the element 5?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look at the 'Stack After' column in the execution table to see when 5 appears.
If the input array was [4, 3, 2, 1], what would be the next greater element for 1?
A-1
B2
C3
D4
💡 Hint
Consider the stack behavior when all elements are in decreasing order from left to right.
Concept Snapshot
Next Greater Element Using Stack:
- Scan array from right to left
- Use stack to track candidates
- Pop smaller/equal elements
- If stack empty, assign -1
- Else top is next greater element
- Push current element onto stack
- Repeat for all elements
Full Transcript
This visualization shows how to find the next greater element for each item in an array using a stack. We start from the rightmost element and move left. For each element, we remove smaller or equal elements from the stack because they cannot be the next greater element. If the stack is empty, it means no greater element exists to the right, so we assign -1. Otherwise, the top of the stack is the next greater element. We then push the current element onto the stack and continue. The execution table tracks the stack and result array after each step, showing how the next greater elements are assigned.

Practice

(1/5)
1. What does the Next Greater Element (NGE) problem using a stack find for each element in an array?
easy
A. The first greater element to the right of each element
B. The first smaller element to the left of each element
C. The last element in the array
D. The sum of all elements greater than the current element

Solution

  1. Step 1: Understand the problem definition

    The Next Greater Element problem asks for the first element to the right of each element that is greater than it.
  2. Step 2: Identify the role of the stack

    The stack helps efficiently find this next greater element by storing candidates and popping smaller elements.
  3. Final Answer:

    The first greater element to the right of each element -> Option A
  4. Quick Check:

    Next Greater Element = first greater right element [OK]
Hint: Look right for the first bigger number using a stack [OK]
Common Mistakes:
  • Confusing next greater with next smaller element
  • Looking to the left instead of right
  • Thinking it sums elements instead of finding one
2. Which of the following C code snippets correctly initializes an empty stack for Next Greater Element problem?
easy
A. int stack[100]; int top = -1;
B. int stack[] = {0}; int top = 0;
C. int *stack; int top = NULL;
D. stack = new int[100]; top = -1;

Solution

  1. Step 1: Check valid C array and top initialization

    int stack[100]; int top = -1; declares a fixed size array and sets top to -1 indicating empty stack.
  2. Step 2: Identify invalid syntax or semantics in other options

    int stack[] = {0}; int top = 0; initializes top to 0 which means stack is not empty; int *stack; int top = NULL; uses NULL for int top which is invalid; stack = new int[100]; top = -1; uses 'new' which is C++ syntax, not C.
  3. Final Answer:

    int stack[100]; int top = -1; -> Option A
  4. Quick Check:

    Stack array + top = -1 means empty [OK]
Hint: Use array and top = -1 for empty stack in C [OK]
Common Mistakes:
  • Using C++ 'new' keyword in C code
  • Initializing top to 0 instead of -1
  • Using pointer without allocation
3. What is the output of the Next Greater Element array for input [4, 5, 2, 25] using the stack method?
medium
A. [25, 25, -1, -1]
B. [5, 2, 25, -1]
C. [5, 25, 25, -1]
D. [-1, -1, -1, -1]

Solution

  1. Step 1: Process each element to find next greater

    For 4, next greater is 5; for 5, next greater is 25; for 2, next greater is 25; for 25, no greater element, so -1.
  2. Step 2: Confirm output array

    The output array is [5, 25, 25, -1].
  3. Final Answer:

    [5, 25, 25, -1] -> Option C
  4. Quick Check:

    Next greater elements match output [OK]
Hint: Check each element's right side for first bigger number [OK]
Common Mistakes:
  • Assigning smaller or wrong next greater values
  • Using -1 for elements that do have greater elements
  • Confusing order of output
4. Identify the bug in this C code snippet for Next Greater Element using stack:
for (int i = 0; i < n; i++) {
  while (top != -1 && arr[stack[top]] < arr[i]) {
    result[stack[top]] = arr[i];
    top--;
  }
  stack[++top] = i;
}
while (top != -1) {
  result[stack[top]] = 0;
  top--;
}
medium
A. Using post-increment instead of pre-increment on stack index
B. Assigning 0 instead of -1 for elements with no greater element
C. Incorrect loop condition causing infinite loop
D. Not initializing top before loop

Solution

  1. Step 1: Check final assignment for elements with no next greater

    The code assigns 0 instead of -1, which is incorrect as per problem definition.
  2. Step 2: Verify other parts of code

    Stack index increment and loop conditions are correct; top is assumed initialized before.
  3. Final Answer:

    Assigning 0 instead of -1 for elements with no greater element -> Option B
  4. Quick Check:

    No greater element should be -1, not 0 [OK]
Hint: Use -1 for no next greater element, not 0 [OK]
Common Mistakes:
  • Using 0 instead of -1 for no next greater
  • Forgetting to initialize top
  • Wrong increment operator on stack
5. Given the array [13, 7, 6, 12], what is the Next Greater Element array using the stack approach? Also, explain why the last element's next greater is -1.
hard
A. [ 7, 12, 13, -1 ]
B. [ -1, 13, 12, -1 ]
C. [ -1, 12, -1, -1 ]
D. [ -1, 12, 12, -1 ]

Solution

  1. Step 1: Find next greater for each element

    For 13, no greater element to right, so -1; for 7, next greater is 12; for 6, next greater is 12; for 12, no greater element, so -1.
  2. Step 2: Explain last element's next greater

    The last element 12 has no elements to its right, so no next greater element exists, hence -1.
  3. Final Answer:

    [ -1, 12, 12, -1 ] -> Option D
  4. Quick Check:

    Last element no right neighbor = -1 [OK]
Hint: Last element always has -1 as no elements to right [OK]
Common Mistakes:
  • Assigning next greater to last element
  • Mixing up next greater for middle elements
  • Confusing output order
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard