Next Greater Element II
LeetCode 503 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
Loop 2n−1 → 0 with i % n; monotonic stack.
నేను Next Greater Element II (LeetCode 503) ను ఇలా పరిష్కరించాను — Monotonic Stack – Next / Previous Greater or Smaller ప్యాటర్న్లోని ఒక మధ్యస్థం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.
కింది వివరణ ఇంగ్లీష్లో ఉంది.
Intuition
Circular array: pretend it's written twice. Scan from the right end of that doubled array keeping a stack of candidates; pop anything not greater than the current value — the stack top is then its next greater element.
Approach
- 1
for i from 2n−1 down to 0, cur = nums[i % n].
- 2
Pop while cur ≥ top value.
- 3
res[i % n] = top value or −1.
- 4
Push i % n.
నేను ఎలా పరిష్కరించాను
Monotonic stack, doubled scanPythonO(n) time
class Solution:
def nextGreaterElements(self, nums: List[int]) -> List[int]:
#start from right part of the array
#if current element in nums is greater than stack's peek, pop it
#if the stack is empty then current element's next greater element is -1 else stack's top eleemnt
#push the elemnet
n = len(nums)
stack =[]
res= [-1]*(n)
for i in range(2*n-1,-1,-1):
curNum = nums[i%n]
while stack and curNum>=nums[stack[-1]]:
stack.pop()
res[i%n]=nums[stack[-1]] if stack else -1
stack.append(i%n)
return res
Next Greater Element II — తరచూ అడిగే ప్రశ్నలు
Next Greater Element II వెనుక ఉన్న intuition ఏమిటి?
Circular array: pretend it's written twice. Scan from the right end of that doubled array keeping a stack of candidates; pop anything not greater than the current value — the stack top is then its next greater element.
Next Greater Element II (LeetCode 503) ను ఎలా పరిష్కరించాలి?
1. for i from 2n−1 down to 0, cur = nums[i % n]. 2. Pop while cur ≥ top value. 3. res[i % n] = top value or −1. 4. Push i % n.
Next Greater Element II యొక్క time, space complexity ఎంత?
Time: O(n). Space: O(n). (Accepted approach: Monotonic stack, doubled scan.)
Next Greater Element II లో సాధారణ పొరపాట్లు ఏమిటి?
Pop on equal values too — 'greater' is strict.