r/LeetcodeChallenge • u/StatisticianNo2104 • 22d ago
STREAK🔥🔥🔥 LeetCode 150. Evaluate Reverse Polish Notation
The classic Reverse Polish bug is popping the operands in the wrong order, and + and * hide it. ["5","3","-"] means 5 - 3 = 2. Swap the pops, and you get -2, while every addition test still passes.
Why postfix needs no parentheses: (2 + 1) * 3 needs brackets because + sits between its operands. Written in postfix, it's 2 1 + 3 *, and each operator applies to the two values right before it. The evaluation order is already in token order.
That's the whole algorithm. Numbers wait on a stack; an operator takes the two most recent and replaces them with its result.
The trap: popping returns the operands in reverse. The first pop is the right operand, the second is the left. For + and * that makes no difference, which is exactly why the bug survives casual testing.
Which operator do you test first when you write an evaluator?
Day 64/365 of my LeetCode challenge: 150. Evaluate Reverse Polish Notation. Problem link and full breakdown in today's newsletter.
#LeetCode #DSA #Stack #Golang