Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 496 · Monotonic Stack – Next / Previous Greater or Smaller

Next Greater Element I

LeetCode 496 · எளிது · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

Monotonic decreasing stack over nums2 + hash map.

எளிதுArrayHash TableStackMonotonic Stack
LeetCode இல் திற ↗

நான் Next Greater Element I (LeetCode 496) ஐ இப்படித் தீர்த்தேன் — Monotonic Stack – Next / Previous Greater or Smaller பேட்டர்னின் ஒரு எளிது பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.

கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.

Intuition

Find the next greater element for every number in nums2 once, using a monotonic stack: a number waits on the stack until a bigger number arrives and resolves it. Then answer nums1 with lookups.

Approach

  1. 1

    Scan nums2; while the current value beats the stack top, pop it and record the answer.

  2. 2

    Push the current index.

  3. 3

    For each value in nums1, read the map (default −1).

நான் எப்படித் தீர்த்தேன்

Monotonic stack + mapPythonO(n+m) time
class Solution:
    def nextGreaterElement(self, nums1: list[int], nums2: list[int]) -> list[int]:
        """
        [4,1,2]
        [1,3,4,2]

        [-1,3,-1]
        monotonic stack - monotoncally increasing stack
        """
        stack = []
        n = len(nums2)
        hash_map = {}
        i=0
        while i<n:
            while stack and nums2[i]>nums2[stack[-1]]:
                index = stack.pop()
                hash_map[nums2[index]]=nums2[i]
            stack.append(i)
            i+=1
        res = []
        for num in nums1:
            if num in hash_map:
                res.append(hash_map[num])
            else:
                res.append(-1)
        return res
        
ஸ்டெப்-த்ரூ ஏற்றுகிறது…

Next Greater Element I — அடிக்கடி கேட்கப்படும் கேள்விகள்

Next Greater Element I பின்னாலுள்ள intuition என்ன?

Find the next greater element for every number in nums2 once, using a monotonic stack: a number waits on the stack until a bigger number arrives and resolves it. Then answer nums1 with lookups.

Next Greater Element I (LeetCode 496) ஐ எப்படித் தீர்ப்பது?

1. Scan nums2; while the current value beats the stack top, pop it and record the answer. 2. Push the current index. 3. For each value in nums1, read the map (default −1).

Next Greater Element I இன் time மற்றும் space complexity என்ன?

Time: O(n + m). Space: O(n). (Accepted approach: Monotonic stack + map.)

Next Greater Element I இல் பொதுவான தவறுகள் என்ன?

Values are unique, so mapping by value is safe.