Practice
Data Structures and Algorithms
Machine Coding Round (LLD)
System Design & Architecture (HLD)
Frontend UI Machine Coding
Resources
Career Advice and Roadmaps
Data Structures and Algorithms
Machine Coding Round (LLD)
System Design & Architecture (HLD)
Backend Development
Frontend Development
Project Ideas for Software Developers
Core Computer Science
Companies
SDE Jobs & Internships
Interview Questions
Compare Companies
IDE
Online IDE
Collaborative IDE

Next Greater Element Editorial

DSA Editorial, Solution and Code

Practice Problem Link: Next Greater Element

Please make sure to try solving the problem yourself before looking at the editorial.

Problem Statement

Given an array of positive integers A, find the first greater number for every element on its right. If a greater number does not exist, use -1.

Naive Approach

We can use two nested loops, to search for the next greater element of the ith element in the array. If we find the next greater element, we push it into the list, else we push -1 into the list and finally return it.

Analysis

  • Time Complexity: O(n2)
  • Space Complexity: O(1)

Implementation

C++
vector<int> getNextGreaterElement (vector<int> &A) {
	int n = A.size();
	vector<int> nextGreater;
	for(int i = 0; i < n; i++) {
		bool possible = false;
		for(int j = i + 1; j < n; j++) {
			if(A[j] > A[i]) {
				nextGreater.push_back(A[j]);
				possible = true;
				break;
			}
		}
		if(!possible) {
			nextGreater.push_back(-1);
		}
	}
	return nextGreater;
}
Java
class Solution {
	int[] getNextGreaterElement (int[] A) {
		int n = A.length;
		int nextGreater[] = new int[n];
		for(int i = 0; i < n; i++) {
			nextGreater[i] = -1;
		}
		for(int i = 0; i < n; i++) {
			for(int j = i + 1; j < n; j++) {
				if(A[j] > A[i]) {
					nextGreater[i] = A[j];
					break;
				}
			}
		}
		return nextGreater;
	}
}

Optimal Approach

We can use stack to optimize the above approach. The steps for the algorithm are,

  1. Push the first element to the stack.
  2. For the remaining element, mark the current element as next.
  3. If the stack is not empty, compare the top element of the stack with next.
  4. If next > top, pop from the stack, nextis the next greater element of the popped element.
  5. We keep popping from the stack, till nextis greater the top of the stack, next is the next greater element for all these popped elements.
  6. Finally, we push next into the stack.
  7. At the end, pop all the remaining elements from the stack and store their next greater element as -1.

Finally we can return the calculated list.

Analysis:

  • Time Complexity: O(n)
  • Space Complexity: O(n)

Implementation:

C++
vector<int> getNextGreaterElement (vector<int> &A) {
	int n = A.size();
	stack<int> s; 
	vector<int> nextGreater(n);
    for (int i = n - 1; i >= 0; i--){
        while(!s.empty() && A[s.top()] <= A[i]) {
			s.pop();
		}
        if(s.empty()) {
			nextGreater[i] = -1;
		}
        else {
			nextGreater[i] = A[s.top()];
		}
        s.push(i);
    }
    return nextGreater;
}
Java
class Solution {
	int[] getNextGreaterElement (int[] A) {
		Stack<Integer> stack = new Stack<>();
		ArrayList<Integer> nextGreater = new ArrayList<>();
        for (int i = A.length - 1; i >= 0; i--) {
            while (!stack.empty() && A[i] >= stack.peek()) {
                stack.pop();
			}
            nextGreater.add(stack.empty() ? -1 : stack.peek());
            stack.push(A[i]);
        }
		int result[] = new int[A.length];
		int k = 0;
         for (int i = A.length - 1; i >= 0; i--) {
            result[i] = nextGreater.get(k++);
		 }
		return result;
	}
}
Related Content
Balanced Parentheses
Evaluate Reverse Polish Notation
Implement Queue using Stacks
Implement Stack using Array
Implement Stack using Linked List
Implement Stack using Queues
Largest Rectangle in Histogram
Implement Min Stack
Trapping Rain Water
SDE Bootcamp - Become a software engineer at a product-based company
Practice Data Structures & Algorithms
Learning Resources
Interview Prep Resources
Community
Join our community
Blog
  • Career Advice and Roadmaps
  • Data Structures & Algorithms
  • Machine Coding Round (LLD)
  • System Design & Architecture
  • Backend Development
  • Frontend Development
  • Awesome Project Ideas
  • Core Computer Science
Practice Questions
  • Machine Coding (LLD) Questions
  • System Design (HLD) Questions
  • Topic-wise DSA Questions
  • Company-wise DSA Questions
  • DSA Sheets (Curated Lists)
  • JavaScript Interview Questions
  • Frontend UI Machine Coding Questions
Online Compilers (IDE)
  • Online Java Compiler
  • Online C++ Compiler
  • Online C Compiler
  • Online Python Compiler
  • Online JavaScript Compiler
Topic-wise Problems
  • Dynamic Programming Interview Questions
  • Linked List Interview Questions
  • Graph Interview Questions
  • Backtracking Interview Questions
  • Arrays Interview Questions
  • Trees Interview Questions
Company-wise Problems
  • Amazon Interview Questions
  • Microsoft Interview Questions
  • Google Interview Questions
  • Flipkart Interview Questions
  • Adobe Interview Questions
  • Facebook Interview Questions
DSA Sheets (Curated Lists)
  • Top Interview Questions
  • FAANG Interview Questions
  • Most Asked Interview Questions
  • 6 month DSA Practice Sheet
  • 3 month DSA Practice Sheet
  • Last minute DSA Practice Sheet