Simulate a Stack from Push, Pop and End-of-Input Commands
Company: Wex
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Online Assessment
Overview: A coding problem that simulates a stack from a stream of text commands: push an integer, pop and output the top value, or end the input. It tests careful token parsing, signed integers and returning the popped values in the order they were removed.
Constraints
- The input has between 1 and 200,000 tokens.
- -10^9 <= num <= 10^9
- Every O is issued while the stack is non-empty.
- U is always followed by exactly one integer token, written in decimal with an optional leading '-'.
- X appears exactly once, as the last token.
- Tokens are separated by one or more whitespace characters (spaces or newlines).
Examples
Input: ('X',)
Expected Output: []
Explanation: Minimum valid stream: X alone ends the input before any command runs, so nothing is output.
Input: ('U 42 X',)
Expected Output: []
Explanation: Singleton push that is still on the stack at X is not output.
Hints
- Two neighbouring tokens can be separated by several spaces or newlines, so break the input on runs of whitespace rather than on a single space character.
- A `U` token is never meaningful on its own: the token right after it is the value to store.
- Each `O` reports the most recently stored value that has not been reported yet, and anything still stored when `X` arrives is never reported.