File: next-greater-element-i/solution.py

Date: 2026-06-06

Time: 18:12

Purpose

This file solves LeetCode 496 — Next Greater Element I. Given two arrays nums1 (a subset of nums2), it finds, for each element in nums1, the first element in nums2 that is strictly greater and appears to its right. Returns -1 when no such element exists.

It's a standalone solution module following the repo's convention: one directory per problem, each containing solution.py, test_solution.py, plan.md, and review.md.

Key Components

nextgreaterelement(nums1, nums2) -> list[int] — The sole public function. Precomputes a next-greater mapping for all elements in nums2, then answers each query from nums1 via dictionary lookup.

Patterns

Monotonic stack — This is the textbook application. The stack maintains a decreasing sequence of unresolved values. When a new value num arrives that's larger than the stack top, all smaller values on the stack have found their answer. The while loop pops and records them all before pushing num.

This separates the problem into two phases:

1. Precomputation (lines 14–18): Single pass over nums2 builds the full next_greater map in O(n).

2. Query (line 20): Each nums1 lookup is O(1) via dict.get.

This two-phase approach avoids the naive O(n*m) nested search.

Dependencies

Imports: None — pure standard library, no external dependencies.

Imported by: next-greater-element-i/testsolution.py and (per the importedby list) hundreds of other test files across the repo — likely because a shared test runner or fixture mechanism imports solution modules generically, not because those tests actually use this function.

Flow

1. Initialize empty next_greater dict and empty stack.

2. Iterate each num in nums2:

3. After the loop, any values still on the stack have no next greater element — they're simply never added to next_greater.

4. Map each element of nums1 through next_greater.get(num, -1), returning -1 for unresolved values.

Concrete tracenums2 = [1, 3, 4, 2]:

Invariants

Error Handling

None. The function trusts its inputs per LeetCode constraints. dict.get with default -1 is the only defensive measure — it handles both "no next greater exists" and (implicitly) "value not in nums2" identically.

Complexity

Topics to Explore

Beliefs