A stack holds the items that are still waiting for something: an opening bracket waiting for its close, a number waiting for an operator, a day waiting for a warmer one. You only look at the top, the newest waiting item, because it is the first one the next input can resolve.
Say what the stack holds, and the code follows. For brackets, it holds every opener not yet closed, in order, so a closer must match the top. For the next warmer day, it holds the days with no warmer day yet. Their readings never rise from bottom to top, so a new reading pops cooler days until it meets one that isn't cooler.
Each item is pushed once and popped at most once, so a stack pass is O(n) time even with a loop inside the loop, plus O(n) space for the stack. Test the cases that break stack code: a pop on an empty stack, items left over at the end, operands popped in the wrong order, and equal values.
temps = [12, 10, 11, 15, 9]
day 0 (12): stack empty, push 0 stack [0]
day 1 (10): not warmer than 12, push 1 stack [0, 1]
day 2 (11): warmer than day 1, answer[1] = 1, pop; push 2
stack [0, 2]
day 3 (15): warmer than day 2, answer[2] = 1, pop;
warmer than day 0, answer[0] = 3, pop; push 3
stack [3]
day 4 (9): not warmer than 15, push 4 stack [3, 4]
days 3 and 4 never warm up: answer = [3, 1, 1, 0, 0]
A warmer reading resolves every cooler day on top of the stack at once, and each day is pushed and popped only once.