0% found this document useful (0 votes)
23 views1 page

Next Greater Element in Stacks and Queues

The Next Greater Element (NGE) problem involves finding the first greater element to the right of each element in an array, with -1 assigned if no greater element exists. For example, in the array [4, 5, 2, 25], the NGE results in 5 for 4, 25 for 5, 25 for 2, and -1 for 25. A brute force solution using nested loops has a time complexity of O(n^2).

Uploaded by

Asif Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views1 page

Next Greater Element in Stacks and Queues

The Next Greater Element (NGE) problem involves finding the first greater element to the right of each element in an array, with -1 assigned if no greater element exists. For example, in the array [4, 5, 2, 25], the NGE results in 5 for 4, 25 for 5, 25 for 2, and -1 for 25. A brute force solution using nested loops has a time complexity of O(n^2).

Uploaded by

Asif Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

1/26/25, 4:14 PM Next Greater Element in Stacks and Queues

Next Greater Element


The next greater element problem is a common question that is asked in
coding interviews.

Given an array, find the next greater element for each element in the array.
The Next Greater Element (NGE) for an element x is the first greater
element on the right side of x in the array. Elements for which no greater
element exist, the NGE is considered as -1.

Here's an example to illustrate the concept:

Suppose we have the following array:

A = [4, 5, 2, 25]

The solution would be:

NGE for 4 is 5
NGE for 5 is 25
NGE for 2 is 25
NGE for 25 is -1

Explanation:

For element 4, the next greater element in the array is 5.


For element 5, the next greater number is 25.
For element 2, the next greater number is 25 (we skip over 5, as we are
looking for the next greater number directly to the right of 2).
For element 25, there is no greater number in the array, hence, the NGE is
-1.

The brute force way to solve this is by using two nested loops, checking each
element against every other element that follows it to find the NGE, which
leads to an O(n^2) time complexity.

https://www.codechef.com/learn/course/stacks-and-queues/LSTACKS02/problems/STACK13 1/1

You might also like