A monotonic stack is a stack whose elements are monotonically increasing or decreasing. To insert an element into the stack you need to remove elements that are greater/less than the provided element and then put the provided element on top keeping elements order. Usually, inserting in a monotonic stack performed by popping top until we can push an element. So, it is said that to preserve monotonic stack over N elements requires O(N) time complexity. For example.
However, what I don't get, if we represent monotonic stack by sorted array and its size, then, when we are inserting element, we can binary search the position where we are supposed to insert the element and discard the tail by reducing size. It seems like to be more efficient approach. The question is, does it change complexity? Is there a reason, why it is usually presented with the iterative "popping top" version?
1 Answer 1
Binary search worsens the time complexity from O(N) to O(N log N).
-
$\begingroup$ hmmmm.... it could be a thing but I find it hard to believe $\endgroup$Irdis– Irdis2024年12月22日 20:23:47 +00:00Commented Dec 22, 2024 at 20:23
-
$\begingroup$ @Irdis What's hard to believe? $\endgroup$Kelly Bundy– Kelly Bundy2024年12月22日 20:28:51 +00:00Commented Dec 22, 2024 at 20:28
-
$\begingroup$ your statement. I see the point that each time we spend log time to find insertion point, so it has to be like n log n. But using the same argument, I can say every time we spend linear time to find insertion point in linear version, so it has to be the square time. But it is incorrect. $\endgroup$Irdis– Irdis2024年12月22日 20:34:09 +00:00Commented Dec 22, 2024 at 20:34
-
1$\begingroup$ I actually think you are right and it is simple as that, in the worst case for bin search when elements to insert are sorted in the same direction, linear version would clearly outperform. $\endgroup$Irdis– Irdis2024年12月22日 23:04:25 +00:00Commented Dec 22, 2024 at 23:04
-
1$\begingroup$ @Irdis Tip for the future just in case you didn't know: There's no rush with awarding bounties. You had "paid" for a week of extra attention that could've attracted more/better answers (while I do think mine is pretty much all that needed to be said, more could be said). If you do what D.W. requested, maybe they'll still post something interesting. $\endgroup$Kelly Bundy– Kelly Bundy2024年12月23日 17:43:35 +00:00Commented Dec 23, 2024 at 17:43
this.size = 0. I also consider case when we don't have to resize in case it too short for simplicity $\endgroup$