Easy dsa stack

Next Greater Element I

The 30 second answer

nums1 is a subset of nums2, and for each value in nums1 I need the first larger value to its right in nums2, or -1. I scan nums2 once with a decreasing stack: when a new value is larger than the top, it is the next greater of that top, and I record it in a map. Then I look up each nums1 value in the map.

Could you say this in an interview?

Problem nums1 is a subset of nums2, and all values in nums2 are unique. For each value in nums1, find the first strictly greater value to its right in nums2, or -1 if none exists, and return those answers in nums1's order. Original: LeetCode 496: Next Greater Element I.

Understanding the prompt The next greater is taken in nums2, not in nums1. Uniqueness lets you key a map by value. You can afford to precompute the answer for every value of nums2, then query.

Pattern recognition A monotonic decreasing stack for the next greater element to the right, plus a hash map for the subset queries.

Brute force For each nums1 value, find it in nums2 and scan to the right: O(n1 · n2).

Optimal Walk nums2 from left to right, holding a decreasing stack of unresolved values. While the current value is greater than the top, pop and record current as that top's next greater in a map. Push current. Values left on the stack have no next greater. Then fill the answer array from the map, defaulting to -1.

Alternatives Walk nums2 from the right with the same decreasing stack, which also works. Daily Temperatures is the same pattern, storing distances instead of values.

Java solution

import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.HashMap;

public class NextGreaterElementI {
    static int[] nextGreaterElement(int[] nums1, int[] nums2) {
        var next = new HashMap<Integer, Integer>();
        var st = new ArrayDeque<Integer>();
        for (int x : nums2) {
            while (!st.isEmpty() && x > st.peek()) next.put(st.pop(), x);
            st.push(x);
        }
        var ans = new int[nums1.length];
        for (int i = 0; i < nums1.length; i++) ans[i] = next.getOrDefault(nums1[i], -1);
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(nextGreaterElement(new int[] {4, 1, 2}, new int[] {1, 3, 4, 2}))); // [-1, 3, -1]
        System.out.println(Arrays.toString(nextGreaterElement(new int[] {2, 4}, new int[] {1, 2, 3, 4})));    // [3, -1]
    }
}

Complexity O(n1 + n2) time, because each nums2 value is pushed and popped at most once. O(n2) extra space for the stack and the map.

Edge cases

  • Official samples: nums1 = [4,1,2], nums2 = [1,3,4,2] returns [-1,3,-1]; nums1 = [2,4], nums2 = [1,2,3,4] returns [3,-1].
  • The last element of nums2 always answers -1.

Follow-ups

  • Next Greater Element II is the circular version: concatenate a logical second pass, or walk the array twice.
  • Daily Temperatures asks for the distance to the next greater, not the value.

Tests nums1 [4,1,2] and nums2 [1,3,4,2] return [-1,3,-1]. nums1 [2,4] and nums2 [1,2,3,4] return [3,-1].

How to say it in the interview "I precompute the next greater value for every element of nums2 with a decreasing stack: when a larger value arrives, it is the answer for everything smaller on the top. I store those in a map and look up each nums1 value. Linear time."

Sources (2)
  1. LeetCode 496: Next Greater Element Ileetcode.com
  2. Java SE 17 API: HashMapdocs.oracle.com