Given a string of nested ternary expressions T?T:F, evaluate right-to-left with a stack. Example: T?T?F:5:3 → F. Scan from the end; on ?, resolve using the condition.
TimeO(n)
SpaceO(n)stack
Step0
stack: []
Ready
Press Play or Step.
✎ Whiteboard
3
⌨ Type It
Practice until you don't need to look. Green highlights are the nuances to burn into memory.
═══ TERNARY EXPRESSION PARSER ═══
PATTERN ▸ right-to-left stack O(n) · O(n)
① SCAN FROM END
for c in reversed(expression)
② ON '?'
t = stack.pop(); f = stack.pop()
stack.append(t if cond == 'T' else f)
③ ELSE
if c != ':': stack.append(c); remember cond on letter before '?'