Javascript Program To Find Next Greater Element
Last Updated :
17 Dec, 2021
Given an array, print the Next Greater Element (NGE) for every element. The Next greater Element 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, consider the next greater element as -1.
Examples:
- For an array, the rightmost element always has the next greater element as -1.
- For an array that is sorted in decreasing order, all elements have the next greater element as -1.
- For the input array [4, 5, 2, 25], the next greater elements for each element are as follows.
Element NGE
4 --> 5
5 --> 25
2 --> 25
25 --> -1
d) For the input array [13, 7, 6, 12}, the next greater elements for each element are as follows.
Element NGE
13 --> -1
7 --> 12
6 --> 12
12 --> -1
Method 1 (Simple)
Use two loops: The outer loop picks all the elements one by one. The inner loop looks for the first greater element for the element picked by the outer loop. If a greater element is found then that element is printed as next, otherwise, -1 is printed.
Below is the implementation of the above approach:
JavaScript
<script>
// Simple JavaScript program to print
// next greater elements in a
// given array
/* prints element and NGE pair
for all elements of arr[] of size n */
function printNGE(arr, n)
{
var next, i, j;
for (i = 0; i < n; i++)
{
next = -1;
for (j = i + 1; j < n; j++)
{
if (arr[i] < arr[j])
{
next = arr[j];
break;
}
}
document.write(arr[i] + " -- " + next);
document.write("<br>");
}
}
// Driver Code
var arr = [11, 13, 21, 3];
var n = arr.length;
printNGE(arr, n);
// This code is contributed by rdtank.
</script>
Output11 -- 13
13 -- 21
21 -- -1
3 -- -1
Time Complexity: O(N2)
Auxiliary Space: O(1)
Method 2 (Using Stack)
- Push the first element to stack.
- Pick rest of the elements one by one and follow the following steps in loop.
- Mark the current element as next.
- If stack is not empty, compare top element of stack with next.
- If next is greater than the top element, Pop element from stack. next is the next greater element for the popped element.
- Keep popping from the stack while the popped element is smaller than next. next becomes the next greater element for all such popped elements.
- Finally, push the next in the stack.
- After the loop in step 2 is over, pop all the elements from the stack and print -1 as the next element for them.
Below image is a dry run of the above approach:
Below is the implementation of the above approach:
JavaScript
<script>
// A Stack based Javascript program to find next
// greater element for all array elements.
/* prints element and NGE pair for all
elements of arr[] of size n */
function printNGE(arr, n)
{
var s = [];
/* push the first element to stack */
s.push(arr[0]);
// iterate for rest of the elements
for (var i = 1; i < n; i++)
{
if (s.length == 0) {
s.push(arr[i]);
continue;
}
/* if stack is not empty, then
pop an element from stack.
If the popped element is smaller
than next, then
a) print the pair
b) keep popping while elements are
smaller and stack is not empty */
while (s.length ==0 == false
&& s[s.length-1] < arr[i])
{
document.write( s[s.length-1]
+ " --> " + arr[i]+"<br>");
s.pop();
}
/* push next to stack so that we can find
next greater for it */
s.push(arr[i]);
}
/* After iterating over the loop, the remaining
elements in stack do not have the next greater
element, so print -1 for them */
while (s.length !=0) {
document.write( s[s.length-1] + " --> " + -1+ "<br>" );
s.pop();
}
}
/* Driver code */
var arr = [11, 13, 21, 3];
var n = arr.length;
printNGE(arr, n);
</script>
Output11 --> 13
13 --> 21
3 --> -1
21 --> -1
Time Complexity: O(N)
Auxiliary Space: O(N)
The worst case occurs when all elements are sorted in decreasing order. If elements are sorted in decreasing order, then every element is processed at most 4 times.
- Initially pushed to the stack.
- Popped from the stack when next element is being processed.
- Pushed back to the stack because the next element is smaller.
- Popped from the stack in step 3 of the algorithm.
How to get elements in the same order as input?
The above approach may not produce output elements in the same order as the input. To achieve the same order, we can traverse the same in reverse order
Below is the implementation of the above approach:
JavaScript
<script>
// Javascript program for the above approach
/* prints element and NGE pair for all
elements of arr[] of size n */
function printNGE(arr, n)
{
var s = [];
let res = new Array(n);
// iterate for rest of the elements
for (let i = n - 1; i >= 0; i--)
{
/* if stack is not empty, then
pop an element from stack.
If the popped element is smaller
than next, then
a) print the pair
b) keep popping while elements are
smaller and stack is not empty */
if (s.length != 0)
{
while (s.length != 0
&& s[s.length-1] <= arr[i])
{
s.pop();
}
}
res[i] = s.length == 0 ? -1 : s[s.length-1];
s.push(arr[i]);
}
for (let i = 0; i < arr.length; i++)
document.write(arr[i] +
" --> " + res[i] + "<br/>");
}
// Driver Code
let arr = [ 11, 13, 21, 3 ];
let n = arr.length;
// Function call
prletNGE(arr, n);
// This code is contributed by splevel62.
</script>
Output11 ---> 13
13 ---> 21
21 ---> -1
3 ---> -1
Time Complexity: O(N)
Auxiliary Space: O(N)
Please refer complete article on
Next Greater Element for more details!
Similar Reads
Javascript Program to Find closest number in array
Given an array of sorted integers. We need to find the closest value to the given number. Array may contain duplicate values and negative numbers. Examples: Input : arr[] = {1, 2, 4, 5, 6, 6, 8, 9} Target number = 11 Output : 9 9 is closest to 11 in given array Input :arr[] = {2, 5, 6, 7, 8, 8, 9};
4 min read
JavaScript Program to Find kth Largest/Smallest Element in an Array
JavaScript allows us to find kth largest/smallest element in an array. We are given an array containing some elements, we have to find kth smallest/largest element from the array where k is a number greater than zero and less than equal to the total number of elements present in the array. There are
5 min read
Find Next greater element in Binary Search Tree
Given a binary search tree and a target value, the task is to find the next greater element of the target value in the binary search tree. Examples: Input: 5 / \ 3 7 / \ / \ 2 4 6 8 Target: 4Output: 5Explanation: The next greater element of 4 is 5 Input: 4 / \ 2 6 / \ \ 1 3 8 Target: 6Output: 8Expla
12 min read
Program to find greater value between a^n and b^n
Given three integers a, b and n, the task is to find out greater value between an and bn.Examples: Input: a = 3, b = 4, n = 5 Output: b^n is greater than a^n Value of an is 243 and the value of bn is 1024. So, bn is greater than an.Input: a = -3, b = 2, n = 4 Output: a^n is greater than b^n Value of
5 min read
Next greater element in same order as input
Given an array, print the Next Greater Element (NGE) for every element. The Next greater Element for an element x is the first greater element on the right side of x in array. Elements for which no greater element exist, consider next greater element as -1. The next greater elements should be printe
7 min read
Minimize moves to next greater element to reach end of Array
Given an array nums[] of size N and a starting index K. In one move from index i we can move to any other index j such that there exists no element in between the indices that is greater than nums[i] and nums[j] > nums[i]. Find the minimum number of moves to reach the last index. Print -1 if it i
14 min read
Javascript Program To Delete Nodes Which Have A Greater Value On Right Side
Given a singly linked list, remove all the nodes which have a greater value on the right side. Examples: Input: 12->15->10->11->5->6->2->3->NULL Output: 15->11->6->3->NULL Explanation: 12, 10, 5 and 2 have been deleted because there is a greater value on the right
5 min read
JavaScript Program to find the Nth smallest/largest element from an unsorted Array
In this article, we will see how to find Nth largest and smallest element from an unsorted array. The Nth smallest/largest element from an unsorted array refers to the element that ranks at the Nth position when the array is sorted either in ascending (smallest) or descending (largest) order. It rep
4 min read
JavaScript Program to Find Smallest Number in a Linked List
Given a linked list, the task is to find the smallest number in a linked list in JavaScript. A "linked list" is a data structure to store data where each piece of information is connected to the next one, forming a chain. Each piece has its data and knows where to find the next piece. It's a basic b
3 min read
Next Greater Frequency Element
Given an array, for each element find the value of the nearest element to the right which is having a frequency greater than that of the current element. If there does not exist an answer for a position, then make the value '-1'.Examples: Input: arr[] = [2, 1, 1, 3, 2, 1]Output: [1, -1, -1, 2, 1, -1
9 min read