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.