#496

Next Greater Element I

Easy
ArrayHash TableStackMonotonic StackHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Using a stack allows us to efficiently find the next greater elements in a single pass through nums2. This is because we can keep track of elements for which we haven't found a next greater element yet.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a stack to keep track of elements in nums2 and a map to store the next greater elements.
  2. 2Step 2: Iterate through nums2. For each element, pop elements from the stack until the current element is less than or equal to the top of the stack.
  3. 3Step 3: If the stack is not empty after popping, the current element is the next greater element for the popped elements. Store this in the map.
  4. 4Step 4: For each element in nums1, use the map to get the next greater element and build the result list.
solution.py8 lines
1def nextGreaterElement(nums1, nums2):
2    stack = []
3    next_greater = {}
4    for num in nums2:
5        while stack and stack[-1] < num:
6            next_greater[stack.pop()] = num
7        stack.append(num)
8    return [next_greater.get(num, -1) for num in nums1]

Complexity note: The time complexity is O(n) because we traverse nums2 once, and each element is pushed and popped from the stack at most once. The space complexity is O(n) due to the stack and the map used to store next greater elements.

  • 1Using a stack helps efficiently find the next greater elements in one pass.
  • 2Mapping results allows for quick lookups when processing nums1.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.