STACT10 - Editorial

Problem Link - Next Greater Element Algorithm

Problem Statement:

The algorithm typically uses a stack data structure to keep track of the elements greater than current element.

  • Initialize an empty stack
  • Iterate through the array from right to left: Start from the rightmost element of the array and move towards the left.
  • Pop elements from the stack: For each element in the array, pop elements from the stack until the stack is empty or the element at the top of the stack is greater than the current array element.
  • Find the Next Greater Element (NGE): If the stack is empty, there is no NGE for the current element, otherwise the top of the stack is NGE for current element.
  • Push the current element: Push the current element on the stack as it can be NGE for the remaining elements.

Approach:

The main idea is to use a stack to help us find the Next Greater Element (NGE) for each item in the array by going through the array from the last element to the first. Here’s how it works:

  1. Using a Stack: We use a stack because it allows us to easily keep track of elements and access the most recently added item. This is useful for comparing elements.
  2. Right to Left Traversal: By starting from the end of the array and moving towards the beginning, we can easily find the NGE for each element without needing to check every subsequent element again.
  3. Removing Smaller Elements: For each element we look at, we pop (remove) any elements from the stack that are smaller than the current element. This is because they can’t be the NGE for any previous elements; we only care about elements that are greater.
  4. Finding NGE: After popping smaller elements, if there are still elements left in the stack, the top element of the stack is the NGE for the current element. If the stack is empty, it means there’s no greater element to the right, so we set the NGE to -1.
  5. Storing Results: We store the found NGE in a separate array, and once we’ve processed all elements, we print the results.

This method is efficient because it ensures that each element is pushed and popped from the stack at most once, making the solution fast and straightforward.

Time Complexity:

O(n), where n is the number of elements in the array, as each element is pushed and popped from the stack at most once.

Space Complexity:

O(n), since we are using a stack to hold elements, which in the worst case can grow to the size of the input array.