Tech for good

[Leetcode/Stack] 496. Next Greater Element I 본문

IT/Computer Science

[Leetcode/Stack] 496. Next Greater Element I

Diana Kang 2025. 4. 14. 22:15

class Solution:
    def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
        # Dictionary to store the next greater element for each number in nums2
        next_greater = {}
        stack = []

        # Traverse nums2 in order
        for num in nums2:
            # Maintain a decreasing stack; pop elements smaller than current num
            while stack and num > stack[-1]:
                smaller = stack.pop()
                next_greater[smaller] = num
            stack.append(num)

        # Remaining elements in stack have no greater element
        for num in stack:
            next_greater[num] = -1
        
        # Build result for nums1 using the precomputed dictionary

🔍 How it works:

  • Stack keeps track of numbers for which we haven't found a next greater element yet.
  • As we iterate through nums2, we pop(뺀다) elements from the stack when the current number is greater than the top of the stack — meaning the current number is the next greater element for that top.
  • We map each popped number to its next greater number.
  • For the result, we just look up each number in nums1 using the dictionary.

🌷 Stack

  • push(): 데이터를 넣는다.
  • pop(): 데이터를 꺼낸다.