AlgoMaster Logo

Next Greater Element I

Ashish

Ashish Pratap Singh

easy

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force

The brute force approach is straightforward: For each element in nums1, search for its next greater element in nums2.

Intuition:

  • For each element in nums1, iterate over nums2 to find the index of that element.
  • From that index, search for the first element greater than the current element.
  • If a greater element is found, add it to the result, otherwise, append -1 (indicating no greater element found).

Code:

2. Using a Stack and HashMap

This approach leverages a stack and hashmap to efficiently find the next greater element for all elements in nums2 in a single pass.

Intuition:

  • Use a stack to track elements for which we are finding the next greater element.
  • As we iterate nums2, for each element, pop elements from the stack if the current element is greater because the current element is the "next greater" for those popped elements.
  • Map each popped element to the current element in a hashmap.
  • After processing, for each element in nums1, retrieve the next greater element directly from the hashmap.

Code: