Leetcode Problem 496. Next Greater Element I

496. Next Greater Element I

Leetcode Solutions

Using Stack and HashMap

  1. Initialize an empty stack and an empty hashmap.
  2. Iterate over the nums2 array: a. While the stack is not empty and the current element is greater than the stack's top element, pop the stack and update the hashmap with the popped element as the key and the current element as the value. b. Push the current element onto the stack.
  3. After the loop, pop any remaining elements from the stack and update the hashmap with the popped element as the key and -1 as the value.
  4. Initialize an empty result list.
  5. Iterate over the nums1 array and for each element, look up the next greater element in the hashmap and add it to the result list.
  6. Return the result list.
UML Thumbnail

Brute Force Approach

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...