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]:

  1. Find the unique index pos where nums[pos] == query[i].
  2. Scan rightward across indices j > pos in nums and pick the first value satisfying nums[j] > query[i].
  3. If no element to the right of pos in nums exceeds query[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,000
  • 0 <= len(query) <= 100,000
  • -10^9 <= nums[i], query[i] <= 10^9
  • All integers in nums are distinct.
  • Every integer in query is present in nums (query itself may contain repeated queries).

Step-by-step walkthrough

  1. Clarify the exact lookup rule

    We have an array nums of distinct integers and a list query whose values all exist in nums. For each x in query, we find x's position in nums and report the first value to its right that exceeds x (or -1 when 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 x in nums, stop at the very first number > x.
    • Neighbor order comes strictly from nums: query merely specifies which values to report and in what output order.
  2. Start with a direct scan (and see why it repeats work)

    A straightforward baseline locates x inside nums for 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 ans
    

    On large inputs, if nums holds n descending numbers (such as [20000, 19999, ..., 1]) and query asks for all m = n values, every query walks to the end of nums in O(m * n) total steps. Scanning across [19999, 19998, ...] repeats the exact same failed comparisons over and over.

  3. Key idea: precompute every answer in one sweep using a waiting stack

    Rather than scanning nums separately per query, sweep nums once from left to right, record the answer for every resolved element in a dictionary next_greater, and answer each query afterward in O(1) time.

    Picture the elements of nums standing in line facing right, and maintain a waiting_stack of 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 store next_greater[smaller_val] = value.
    • Once the stack is empty or its top exceeds value, push value onto waiting_stack so it waits for its own match.

    Because every incoming value pops all smaller items before being pushed, waiting_stack stays strictly decreasing from bottom to top (a monotonic decreasing stack). Watch nums = [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 5 resolves both 2 and 4 in one pass! Any elements still sitting on waiting_stack when the sweep finishes (6 and 5) never met a larger number to their right, so their lookup defaults to -1.

  4. Code the two-phase algorithm

    Because nums contains no duplicates, each integer uniquely identifies its position, letting us key next_greater directly by value.

    Although a while loop sits inside the for loop, Phase 1 takes O(n) total time: each of the n elements in nums is 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 ans
    
  5. Trace Example 1 step by step

    Let's trace query = [8, 3, 2, 5] and nums = [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]
    
  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]:

  1. Read 5, then 3 (3 < 5): stack holds [5, 3]. Read 6: 6 exceeds both 3 and 5, popping them (next_greater[3] = 6, next_greater[5] = 6) and leaving [6].
  2. Read 8: 8 > 6, popping 6 (next_greater[6] = 8) and pushing 8 ([8]). Read 2: 2 < 8, leaving [8, 2] unresolved at the end of the pass.
  3. Looking up query = [8, 3, 2, 5] in next_greater with default -1 returns [-1, 6, -1, 6].

Complexity

Let n = len(nums) and m = len(query).

  • Time: O(n + m). In Phase 1, each of the n integers in nums is pushed onto waiting_stack once and popped at most once, bounding total stack operations to 2n and dictionary insertions to at most n - 1. In Phase 2, each of the m queries performs one O(1) average-time dictionary lookup.
  • Space: O(n + m) (O(n) auxiliary storage plus O(m) for the returned list). In the worst case, waiting_stack stores up to n values, next_greater stores up to n - 1 entries, and ans holds m integers.

Edge cases

  • Empty query (query = []): Phase 2 performs zero lookups and returns [].
  • Single-element nums (nums = [7]): 7 stays on waiting_stack, so querying 7 returns -1.
  • Strictly decreasing nums ([3, 0, -4, -9]): Nothing ever pops from waiting_stack, so every query returns -1 (Example 4).
  • Last element of nums: Has no elements after it, so it always stays on waiting_stack and resolves to -1.
  • Larger values to the left (nums = [10, 4, 9, 7, 8], querying 7): 10 and 9 sit earlier in nums (9 > 7 remains below 7 on the stack), so only right-hand neighbor 8 is considered (Example 2).
  • Repeated entries in query: Phase 2 reads next_greater.get(x, -1) independently for each query element.
  • Negative numbers (including -1): Signed integer comparisons work unchanged; if -1 is genuinely the first larger value after -5, next_greater[-5] = -1 matches the -1 sentinel 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], 4 resolves to 9 (first to the right), not 7 or 8.
  • Looking rightward inside query rather than nums: query only lists lookup keys; neighbor order is defined exclusively by nums.
  • Using next_greater[x] instead of next_greater.get(x, -1): Raises KeyError whenever x remained unresolved on waiting_stack.
  • Building an {x: idx} index dictionary but still scanning right per query: Saves nums.index(x), yet still takes O(m * n) time on descending inputs.
  • Misjudging the nested for + while loop as O(n^2): Every popped element leaves waiting_stack permanently, so total pops across all iterations cannot exceed n.

Alternative approaches

  • Right-to-left monotonic stack: Traverse nums backward from right to left while keeping candidate larger right-hand values on the stack. At each value, pop every stack top <= value (because value sits further left and is at least as large, dominating those popped elements for all earlier positions), read the remaining stack top as next_greater[value] (or -1 if empty), and push value. It matches O(n + m) time and O(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 nums by iterating i from 0 to 2n - 1 and inspecting value = nums[i % n]. Push onto waiting_stack only 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 in O(n) time.
  • What breaks if nums contains duplicate values, and how would you handle positional queries instead? Keying next_greater by integer value breaks because equal values at different indices can have different answers (for instance, the first 3 in [3, 5, 3, 1] resolves to 5 whereas the second 3 resolves to -1). Instead, push array indices onto waiting_stack, check nums[waiting_stack[-1]] < nums[i] (using strict < so equal duplicates do not pop one another), and store answers by position in ans_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 indices i onto waiting_stack instead of values and record cur_idx - smaller_idx when popping. To find the first smaller element to the right, flip the pop condition to waiting_stack[-1] > value, which maintains a monotonic increasing stack from bottom to top.

Follow-up questions

Similar questions

More Temu interview questions

All 4 Temu questions →