The Next Greater Element I problem gives you two arrays, nums1 and nums2, where nums1 is a subset of nums2. For each element in nums1, find the next greater element that appears to its right in nums2. Return -1 if no greater element exists. This Next Greater Element I coding problem is the foundational monotonic stack problem.
Apple, Uber, Goldman Sachs, Microsoft, Meta, Amazon, Google, Bloomberg, and many others ask this as the entry point to the monotonic stack pattern. It validates that candidates understand how a decreasing stack works for "next greater" queries. The array, monotonic stack, hash table, and stack interview pattern is the cornerstone here.
Monotonic decreasing stack + hash map. Process nums2 left to right. Maintain a stack of elements for which we haven't found the next greater yet. For each element x: while the stack top is less than x, the stack top's next greater is x — pop and record in a hash map. Push x onto the stack. After processing, elements remaining on stack have no next greater (-1). Look up each nums1 element in the hash map.
nums2 = [4, 1, 2, 3]. Process:
nums1=[1,4]: answers = [map[1]=2, map[4]=-1] = [2, -1].
stack.top() < x vs ≤ x (strict vs non-strict greater).The monotonic stack for "next greater element" follows a consistent template: iterate left-to-right, maintain a decreasing stack, pop-and-record when current element exceeds the stack top. Memorize this template and practice it for all four variants: next greater, next smaller, previous greater, previous smaller. These four patterns cover the majority of monotonic stack interview questions. Practice until the stack operations feel automatic.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Final Prices With a Special Discount in a Shop | Easy | Solve | |
| Minimum Operations to Convert All Elements to Zero | Medium | Solve | |
| Longest Well-Performing Interval | Medium | Solve | |
| Next Greater Element II | Medium | Solve | |
| Sum of Subarray Ranges | Medium | Solve |