KatInterview

496. Next Greater Element I

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method: Monotonic Stack and Hash Map

This problem asks us to find the "next greater element" for items in nums1 by looking at their positions in nums2. A naive approach would be to iterate through nums1, and for each element, find it in nums2 and then scan the rest of nums2 to find the next greater element. This would result in a time complexity of O(nums1.length * nums2.length), which can be slow. The follow-up hints at a more optimal O(nums1.length + nums2.length) solution, which points towards a single-pass approach.

Solution

Next Greater Element I in Python

class Solution:
    def nextGreaterElement(self, nums1: list[int], nums2: list[int]) -> list[int]:
        # A map to store the next greater element for each number.
        next_greater_map = {}
        # A stack to maintain a monotonically decreasing sequence.
        stack = []

        # Iterate through nums2 to pre-calculate next greater elements.
        for num in nums2:
            # While the stack is not empty and the current number is greater than the stack's top element.
            while stack and num > stack[-1]:
                # The current number is the next greater element for the element at the top of the stack.
                next_greater_map[stack.pop()] = num
            # Push the current number onto the stack. It will wait for its next greater element.
            stack.append(num)
        
        # Build the result list for nums1.
        result = []
        for num in nums1:
            # Get the pre-calculated next greater element from the map.
            # If a number is not in the map, it means it had no next greater element (it was left in the stack).
            # The .get() method with a default value of -1 handles this case elegantly.
            result.append(next_greater_map.get(num, -1))
            
        return result

Next Greater Element I in Java

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.Map;

class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        // Map to store the next greater element for each number.
        Map<Integer, Integer> nextGreaterMap = new HashMap<>();
        // Use a Deque as a stack to maintain a monotonically decreasing sequence.
        Deque<Integer> stack = new ArrayDeque<>();
        
        // Iterate through nums2 to pre-calculate next greater elements.
        for (int num : nums2) {
            // While stack is not empty and current number is greater than stack's top.
            while (!stack.isEmpty() && num > stack.peek()) {
                // The current number is the next greater element for the element at stack's top.
                nextGreaterMap.put(stack.pop(), num);
            }
            // Push current number onto the stack.
            stack.push(num);
        }
        
        // Create the result array for nums1.
        int[] result = new int[nums1.length];
        for (int i = 0; i < nums1.length; i++) {
            // Get the next greater element from the map. If not found, default to -1.
            // This handles elements that were left on the stack (no next greater element).
            result[i] = nextGreaterMap.getOrDefault(nums1[i], -1);
        }
        
        return result;
    }
}

Next Greater Element I in C++

class Solution {
public:
    vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
        // Map to store the next greater element for each number in nums2.
        std::unordered_map<int, int> nextGreaterMap;
        // Stack to maintain a monotonically decreasing sequence of numbers.
        std::stack<int> s;

        // Iterate through nums2 to pre-calculate next greater elements.
        for (int num : nums2) {
            // While the stack is not empty and the current number is greater than the stack's top,
            // it means the current number is the next greater element for the stack's top.
            while (!s.empty() && num > s.top()) {
                nextGreaterMap[s.top()] = num;
                s.pop();
            }
            // Push the current number onto the stack. It will wait for its next greater element.
            s.push(num);
        }
        
        // Prepare the result vector.
        std::vector<int> result;
        result.reserve(nums1.size()); // Optional optimization to pre-allocate memory.
        
        // For each number in nums1, find its next greater element from the map.
        for (int num : nums1) {
            // If the number is found in the map, it has a next greater element.
            if (nextGreaterMap.count(num)) {
                result.push_back(nextGreaterMap[num]);
            } else {
                // Otherwise, it doesn't have one (it was left in the stack).
                result.push_back(-1);
            }
        }
        
        return result;
    }
};

Next Greater Element I in TypeScript

function nextGreaterElement(nums1: number[], nums2: number[]): number[] {
    // Map to store the next greater element for each number.
    const nextGreaterMap = new Map<number, number>();
    // An array used as a stack to maintain a monotonically decreasing sequence.
    const stack: number[] = [];

    // Iterate through nums2 to compute the next greater element for each number.
    for (const num of nums2) {
        // While the stack is not empty and the current number is greater than the top of the stack.
        while (stack.length > 0 && num > stack[stack.length - 1]) {
            // Pop the element from the stack and set its next greater element to the current number.
            // '!' asserts that pop() will not return undefined because we checked stack.length > 0.
            const top = stack.pop()!;
            nextGreaterMap.set(top, num);
        }
        // Push the current number onto the stack.
        stack.push(num);
    }

    // Build the result array by looking up values in the map.
    const result: number[] = [];
    for (const num of nums1) {
        // If a next greater element exists in the map, use it; otherwise, use -1.
        // The nullish coalescing operator '??' provides a default value if .get() returns undefined.
        result.push(nextGreaterMap.get(num) ?? -1);
    }

    return result;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.