Find the next greater element in an array
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
The problem of finding the next greater element (NGE) in an array is a classic algorithmic challenge that is often addressed in coding interviews and competitive programming. The task is to identify the next larger element for each element in a given array. If no such element exists for a specific array entry, we typically return a designated value, such as -1.
This article provides a comprehensive study of the problem, illustrative examples, and various approaches to solving it efficiently.
Problem Statement
Given an array of integers, the objective is to construct a new array (of the same length) where each position contains the next greater element from the right for the corresponding element in the input array. If there's no greater element, store -1 in that position.
Example
Consider the array `[4, 5, 2, 25]`. The respective next greater elements for each element are:
- For `4`, it is `5`.
- For `5`, it is `25`.
- For `2`, it is `25`.
- For `25`, there is no next greater element, so it is `-1`.
Thus, the output array would be `[5, 25, 25, -1]`.
Approaches to Solve the Problem
Naive Approach (O(N^2) Complexity)
The simplest way to solve this problem is to use a nested loop to compare each element with all the subsequent elements to find the next greater element:
- While the stack is not empty and the top of the stack is less than or equal to the current element, pop elements from the stack.
- If the stack is not empty after the above operation, the element at the top of the stack is the next greater element for the current index.
- Push the current element onto the stack.
- Edge Cases:
- Arrays with all elements identical will result in an output array where all elements are -1.
- An empty input array should return an empty output array.
- Applications:
- This problem is not only fundamental in learning how stacks work, but is also applicable in more complex problems like processing spans in stock price trends, evaluating expressions, and in scenarios where a real-time update of maximum value needs to be shown.

