Monotonic stack

What is a Monotonic Stack

A monotonic stack is a stack whose elements are monotonically increasing or decreasing. It contains all properties that a typical stack has and its elements are monotonic decreasing or increasing.

Monotonic increasing stack: [2 3 5 6 9]
Monotonic decreasing stack: [9 6 5 3 2]

[Leetcode 739] Daily Temperatures

Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.

Example 1:

1
2
Input: temperatures = [73,74,75,71,69,72,76,73]
Output: [1,1,4,2,1,1,0,0]

Constraints:

  • 1 <= temperatures.length <= 105
  • 30 <= temperatures[i] <= 100

Solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution:
# e.g. temperatures = [73,74,75,71,69,72,76,73]
# i stack result
# 0 [0] [0, 0, 0, 0, 0, 0, 0, 0]
# 1 [1] [1, 0, 0, 0, 0, 0, 0, 0]
# 2 [2] [1, 1, 0, 0, 0, 0, 0, 0]
# 3 [2, 3] [1, 1, 0, 0, 0, 0, 0, 0]
# 4 [2, 3, 4] [1, 1, 0, 0, 0, 0, 0, 0]
# 5 [2, 5] [1, 1, 0, 2, 1, 0, 0, 0]
# 6 [6] [1, 1, 4, 2, 1, 1, 0, 0]
# 7 [6, 7] [1, 1, 4, 2, 1, 1, 0, 0]
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
st = []
res = [0] * len(temperatures)
for i in range(len(temperatures)):
while st and temperatures[i] > temperatures[st[-1]]:
idx = st.pop()
res[idx] = i - idx

st.append(i)
#print(st, res)

return res

[Leetcode 901] Online Stock Span

Design an algorithm that collects daily price quotes for some stock and returns the span of that stock’s price for the current day.

The span of the stock’s price in one day is the maximum number of consecutive days (starting from that day and going backward) for which the stock price was less than or equal to the price of that day.

  • For example, if the prices of the stock in the last four days is [7,2,1,2] and the price of the stock today is 2, then the span of today is 4 because starting from today, the price of the stock was less than or equal 2 for 4 consecutive days.
  • Also, if the prices of the stock in the last four days is [7,34,1,2] and the price of the stock today is 8, then the span of today is 3 because starting from today, the price of the stock was less than or equal 8 for 3 consecutive days.

Implement the StockSpanner class:

  • StockSpanner() Initializes the object of the class.
  • int next(int price) Returns the span of the stock’s price given that today’s price is price.

Example 1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Input
["StockSpanner", "next", "next", "next", "next", "next", "next", "next"]
[[], [100], [80], [60], [70], [60], [75], [85]]
Output
[null, 1, 1, 1, 2, 1, 4, 6]

Explanation
StockSpanner stockSpanner = new StockSpanner();
stockSpanner.next(100); // return 1
stockSpanner.next(80); // return 1
stockSpanner.next(60); // return 1
stockSpanner.next(70); // return 2
stockSpanner.next(60); // return 1
stockSpanner.next(75); // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price.
stockSpanner.next(85); // return 6

Constraints:

  • 1 <= price <= 105
  • At most 104 calls will be made to next.

Solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class StockSpanner:
def __init__(self):
self.st = []

# e.g.
# (60,1)
# (60,1) (70,2) (70,2) (75,4)
# (80,1) (80,1) (80,1) (80,1) (80,1) (85,6)
# (100,1) (100,1) (100,1) (100,1) (100,1) (100,1) (100,1)
# input: 100 80 60 70 60 75 85
def next(self, price: int) -> int:
span = 1 # span for itself is 1

# accumulate the span with lower(or equal) prices and only save higher price in stack
while self.st and self.st[-1][0] <= price:
prevPrice, prevSpan = self.st.pop()
span += prevSpan

self.st.append((price, span))
return span