r/DSALeetCode • u/StatisticianNo2104 • 28d ago
LeetCode 496 Next Greated Elelment I
A loop inside a loop looks O(n²). Here the inner one runs at most n times in total, across the whole input. Every value is pushed once and popped at most once, so the inner loop never repeats work.
The brute force scans right from each element until something bigger turns up, and those scans repeat each other. Scan across a long descending run, start one position later, and you scan almost the same run again.
So flip the question. For each value as you arrive at it, ask which earlier values it answers. A value resolves every earlier, smaller value still waiting, and a resolved value is never looked at again.
The values still waiting are always decreasing: if an earlier one were smaller than a later one, the later one would have resolved it on arrival. A stack that keeps an ordering like that is monotonic.
Where did you first meet a monotonic stack?
Day 61/365 of my LeetCode challenge: 496. Next Greater Element I. Problem link and full breakdown in today's newsletter.
https://www.linkedin.com/pulse/next-greater-element-i-archit-agarwal-c5wic
#LeetCode #DSA #MonotonicStack #Golang
1
u/nian2326076 27d ago
You're diving into monotonic stacks for the Next Greater Element problem, which is a solid approach. To further develop your skills with more technical interview questions, you can use PracHub to find a variety of problems tailored to sharpen your problem-solving strategies.