Skip to main content
Back to problems
#496
Easy Algorithms

Next greater element i

Array Hash Table Stack Monotonic Stack
75.8% acceptance
Jan 13, 2026
9737
1095
The next greater element of some element x in an array is the first greater element that is to the right of x in the same array. You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2. For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2. If there is no next greater element, then the answer for this query is -1. Return an array ans of length nums1.length such that ans[i] is the next greater element as described above.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
use std::collections::HashMap;

impl Solution {
  pub fn next_greater_element(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> {
    let mut map = HashMap::new();
    let mut stack = Vec::new();
    
    for num in nums2 {
      while !stack.is_empty() && *stack.last().unwrap() < num {
        map.insert(stack.pop().unwrap(), num);
      }
      stack.push(num);
    }
    
    nums1.iter().map(|&n| *map.get(&n).unwrap_or(&-1)).collect()
  }
}