Subset Next Greater Lookup
Easy · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
Given an array nums of pairwise distinct integers and a lookup array query whose entries all occur in nums, determine the first larger right-hand neighbor in nums for every requested value in query.
Specifically, for each entry query[i]:
- Find the unique index
poswherenums[pos] == query[i]. - Scan rightward across indices
j > posinnumsand pick the first value satisfyingnums[j] > query[i]. - If no element to the right of
posinnumsexceedsquery[i], record-1.
Implement next_greater_element(query: List[int], nums: List[int]) -> List[int] and return the answers in the same order as query.
Examples
Example 1
Input:
query = [8, 3, 2, 5]
nums = [5, 3, 6, 8, 2]
Output:
[-1, 6, -1, 6]
Walk-through:
- 8 sits at index 3 of nums; only 2 appears to its right (2 < 8), giving -1.
- 3 sits at index 1; the first element after it exceeding 3 is 6.
- 2 sits at the end of nums with nothing after it, giving -1.
- 5 sits at index 0; 3 is smaller, and the first element exceeding 5 is 6.
Example 2
Input:
query = [4, 7]
nums = [10, 4, 9, 7, 8]
Output:
[9, 8]
Walk-through: After 4 in nums, 9 appears before 7 and 8, so 4 maps to 9 (first larger, not closest in value). For 7, larger values 10 and 9 lie to its left and are ignored, while 8 lies to its right and exceeds 7.
Example 3
Input:
query = [10, 30, 40]
nums = [10, 20, 30, 40]
Output:
[20, 40, -1]
Walk-through: In a strictly ascending array, every non-final element maps to its immediate right neighbor (10 -> 20, 30 -> 40), while the final element 40 maps to -1.
Example 4
Input:
query = [-4, 0, -9]
nums = [3, 0, -4, -9]
Output:
[-1, -1, -1]
Walk-through: nums decreases strictly from left to right, so no element has a larger value after it.
Constraints
1 <= len(nums) <= 100,0000 <= len(query) <= 100,000-10^9 <= nums[i], query[i] <= 10^9- All integers in
numsare distinct. - Every integer in
queryis present innums(queryitself may contain repeated queries).
Step-by-step walkthrough
Clarify the exact lookup rule
We have an array
numsof distinct integers and a listquerywhose values all exist innums. For eachxinquery, we findx's position innumsand report the first value to its right that exceedsx(or-1when nothing to its right is larger).Two pitfalls are worth ruling out up front:
nums = [10, 4, 9, 7, 8] ^ ^ | first element to the right of 4 exceeding 4 is 9 | (NOT 7 or 8, even though they are closer in value, and 10 on the left is ignored!)- Leftmost larger value, not closest larger or overall maximum: Scanning rightward from
xinnums, stop at the very first number> x. - Neighbor order comes strictly from
nums:querymerely specifies which values to report and in what output order.
- Leftmost larger value, not closest larger or overall maximum: Scanning rightward from
Start with a direct scan (and see why it repeats work)
A straightforward baseline locates
xinsidenumsfor each query and scans right until it hits a larger value:def brute_next_greater(query: List[int], nums: List[int]) -> List[int]: ans: List[int] = [] for x in query: found = -1 for j in range(nums.index(x) + 1, len(nums)): if nums[j] > x: found = nums[j] break ans.append(found) return ansOn large inputs, if
numsholdsndescending numbers (such as[20000, 19999, ..., 1]) andqueryasks for allm = nvalues, every query walks to the end ofnumsinO(m * n)total steps. Scanning across[19999, 19998, ...]repeats the exact same failed comparisons over and over.Key idea: precompute every answer in one sweep using a waiting stack
Rather than scanning
numsseparately per query, sweepnumsonce from left to right, record the answer for every resolved element in a dictionarynext_greater, and answer each query afterward inO(1)time.Picture the elements of
numsstanding in line facing right, and maintain awaiting_stackof elements seen so far that still need a larger element to their right:- When visiting
value, inspect the stack top (waiting_stack[-1]). - While
waiting_stack[-1] < value, that waiting number has just encountered its first larger right-hand value! Pop it and storenext_greater[smaller_val] = value. - Once the stack is empty or its top exceeds
value, pushvalueontowaiting_stackso it waits for its own match.
Because every incoming
valuepops all smaller items before being pushed,waiting_stackstays strictly decreasing from bottom to top (a monotonic decreasing stack). Watchnums = [6, 4, 2, 5]:Read 6: waiting_stack = [6] (6 waits) Read 4: 4 < 6, no pops waiting_stack = [6, 4] (strictly decreasing: 6 > 4) Read 2: 2 < 4, no pops waiting_stack = [6, 4, 2] (strictly decreasing: 6 > 4 > 2) Read 5: 2 < 5 -> pop 2, record next_greater[2] = 5 4 < 5 -> pop 4, record next_greater[4] = 5 6 < 5 is False -> stop popping! (6 stays waiting) push 5 -> waiting_stack = [6, 5]Visiting
5resolves both2and4in one pass! Any elements still sitting onwaiting_stackwhen the sweep finishes (6and5) never met a larger number to their right, so their lookup defaults to-1.- When visiting
Code the two-phase algorithm
Because
numscontains no duplicates, each integer uniquely identifies its position, letting us keynext_greaterdirectly by value.Although a
whileloop sits inside theforloop, Phase 1 takesO(n)total time: each of thenelements innumsis pushed once and popped at most once across the entire sweep.def next_greater_element(query: List[int], nums: List[int]) -> List[int]: # next_greater: maps each resolved value v -> first value to the right of v in nums with val > v. next_greater: Dict[int, int] = {} # waiting_stack: values from nums still waiting to see a strictly larger value to their right. # Invariant: strictly decreasing from bottom to top (e.g., [9, 5, 2]), because every new # larger value pops all smaller waiting values before pushing itself. waiting_stack: List[int] = [] # Phase 1: Sweep nums left-to-right to precompute next greater elements in O(n) time. for value in nums: # Every waiting value smaller than `value` has just found its first larger right-hand neighbor. while waiting_stack and waiting_stack[-1] < value: smaller_val = waiting_stack.pop() next_greater[smaller_val] = value # Push `value` onto the stack to wait for a future larger element. waiting_stack.append(value) # Phase 2: Answer each query in O(1) time. # Values still left on waiting_stack never met a larger element, so .get() defaults to -1. ans: List[int] = [] for x in query: ans.append(next_greater.get(x, -1)) return ansTrace Example 1 step by step
Let's trace
query = [8, 3, 2, 5]andnums = [5, 3, 6, 8, 2]:Phase 1: Sweep nums = [5, 3, 6, 8, 2] value = 5: stack empty -> push 5 -> waiting_stack = [5] value = 3: top 5 < 3 is False -> push 3 -> waiting_stack = [5, 3] value = 6: top 3 < 6 -> pop 3 (3 -> 6) top 5 < 6 -> pop 5 (5 -> 6) -> push 6 -> waiting_stack = [6] value = 8: top 6 < 8 -> pop 6 (6 -> 8) -> push 8 -> waiting_stack = [8] value = 2: top 8 < 2 is False -> push 2 -> waiting_stack = [8, 2] End of sweep: next_greater = {3: 6, 5: 6, 6: 8} unresolved on waiting_stack = [8, 2] (both default to -1) Phase 2: Lookup query = [8, 3, 2, 5] x = 8 -> next_greater.get(8, -1) = -1 x = 3 -> next_greater.get(3, -1) = 6 x = 2 -> next_greater.get(2, -1) = -1 x = 5 -> next_greater.get(5, -1) = 6 Result: [-1, 6, -1, 6]Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def next_greater_element(query: List[int], nums: List[int]) -> List[int]: # next_greater: maps each resolved value v -> first value to the right of v in nums with val > v. next_greater: Dict[int, int] = {} # waiting_stack: values from nums still waiting to see a strictly larger value to their right. # Invariant: strictly decreasing from bottom to top (e.g., [9, 5, 2]), because every new # larger value pops all smaller waiting values before pushing itself. waiting_stack: List[int] = [] # Phase 1: Sweep nums left-to-right to precompute next greater elements in O(n) time. for value in nums: # Every waiting value smaller than `value` has just found its first larger right-hand neighbor. while waiting_stack and waiting_stack[-1] < value: smaller_val = waiting_stack.pop() next_greater[smaller_val] = value # Push `value` onto the stack to wait for a future larger element. waiting_stack.append(value) # Phase 2: Answer each query in O(1) time. # Values still left on waiting_stack never met a larger element, so .get() defaults to -1. ans: List[int] = [] for x in query: ans.append(next_greater.get(x, -1)) return ans✅ Submit now — all tests should pass.
Intuition & how it works
Picture people of distinct heights standing in a single-file line (nums), all facing right, where each person wants to record the height of the first taller person ahead of them. Walking down the line from left to right, we maintain a waiting list (waiting_stack) of people who have not yet spotted anyone taller. Whenever a taller newcomer steps up, everyone at the end of the waiting list shorter than that newcomer immediately records the newcomer's height and steps off the list. That structure is a monotonic decreasing stack—a stack whose entries remain strictly decreasing from bottom to top because every new element pops all smaller elements before pushing itself.
Searching nums separately for each query[i] repeats identical rightward scans and degrades to O(m * n) time when nums is sorted in descending order. Precomputing answers across nums in a single pass with a monotonic stack removes all redundant work: each number enters and exits the stack at most once (amortized O(1) work per element, meaning the average cost per step across the entire pass is constant even if one step pops several waiting items), reducing each query to a single O(1) dictionary read.
Trace Example 1 on nums = [5, 3, 6, 8, 2] and query = [8, 3, 2, 5]:
- Read
5, then3(3 < 5): stack holds[5, 3]. Read6:6exceeds both3and5, popping them (next_greater[3] = 6,next_greater[5] = 6) and leaving[6]. - Read
8:8 > 6, popping6(next_greater[6] = 8) and pushing8([8]). Read2:2 < 8, leaving[8, 2]unresolved at the end of the pass. - Looking up
query = [8, 3, 2, 5]innext_greaterwith default-1returns[-1, 6, -1, 6].
Complexity
Let n = len(nums) and m = len(query).
- Time:
O(n + m). In Phase 1, each of thenintegers innumsis pushed ontowaiting_stackonce and popped at most once, bounding total stack operations to2nand dictionary insertions to at mostn - 1. In Phase 2, each of themqueries performs oneO(1)average-time dictionary lookup. - Space:
O(n + m)(O(n)auxiliary storage plusO(m)for the returned list). In the worst case,waiting_stackstores up tonvalues,next_greaterstores up ton - 1entries, andansholdsmintegers.
Edge cases
- Empty
query(query = []): Phase 2 performs zero lookups and returns[]. - Single-element
nums(nums = [7]):7stays onwaiting_stack, so querying7returns-1. - Strictly decreasing
nums([3, 0, -4, -9]): Nothing ever pops fromwaiting_stack, so every query returns-1(Example 4). - Last element of
nums: Has no elements after it, so it always stays onwaiting_stackand resolves to-1. - Larger values to the left (
nums = [10, 4, 9, 7, 8], querying7):10and9sit earlier innums(9 > 7remains below7on the stack), so only right-hand neighbor8is considered (Example 2). - Repeated entries in
query: Phase 2 readsnext_greater.get(x, -1)independently for each query element. - Negative numbers (including
-1): Signed integer comparisons work unchanged; if-1is genuinely the first larger value after-5,next_greater[-5] = -1matches the-1sentinel without conflict because.get(-5, -1)still returns-1.
Common mistakes
- Picking the smallest larger value or overall maximum instead of the first larger value: In
nums = [10, 4, 9, 7, 8],4resolves to9(first to the right), not7or8. - Looking rightward inside
queryrather thannums:queryonly lists lookup keys; neighbor order is defined exclusively bynums. - Using
next_greater[x]instead ofnext_greater.get(x, -1): RaisesKeyErrorwheneverxremained unresolved onwaiting_stack. - Building an
{x: idx}index dictionary but still scanning right per query: Savesnums.index(x), yet still takesO(m * n)time on descending inputs. - Misjudging the nested
for+whileloop asO(n^2): Every popped element leaveswaiting_stackpermanently, so total pops across all iterations cannot exceedn.
Alternative approaches
- Right-to-left monotonic stack: Traverse
numsbackward from right to left while keeping candidate larger right-hand values on the stack. At eachvalue, pop every stack top<= value(becausevaluesits further left and is at least as large, dominating those popped elements for all earlier positions), read the remaining stack top asnext_greater[value](or-1if empty), and pushvalue. It matchesO(n + m)time andO(n)space while recording each element's answer immediately when visited.
Follow-up questions
- How would you modify the algorithm if nums wraps around circularly from the end back to index 0? Run two passes over
numsby iteratingifrom0to2n - 1and inspectingvalue = nums[i % n]. Push ontowaiting_stackonly during the first lap (i < n), while allowing pops on both laps so elements near the tail can be resolved by larger elements near the head inO(n)time. - What breaks if nums contains duplicate values, and how would you handle positional queries instead? Keying
next_greaterby integer value breaks because equal values at different indices can have different answers (for instance, the first3in[3, 5, 3, 1]resolves to5whereas the second3resolves to-1). Instead, push array indices ontowaiting_stack, checknums[waiting_stack[-1]] < nums[i](using strict<so equal duplicates do not pop one another), and store answers by position inans_by_idx[smaller_idx] = nums[i]. - How can the same stack technique return the index distance to the next larger value or find the next smaller value? To return step counts (
j - i), push indicesiontowaiting_stackinstead of values and recordcur_idx - smaller_idxwhen popping. To find the first smaller element to the right, flip the pop condition towaiting_stack[-1] > value, which maintains a monotonic increasing stack from bottom to top.
Follow-up questions
- How would you modify the algorithm if nums wraps around circularly from the end back to index 0?
- What breaks if nums contains duplicate values, and how would you handle positional queries instead?
- How can the same stack technique return the index distance to the next larger value or find the next smaller value?
Similar questions
- Longest Consecutive Login Streaks
- Identify Missing Straight Rank
- Clockwise Spiral Traversal Around Grid Obstacles
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses