Magicsheet logo

Baseball Game

Easy
81.2%
Updated 6/1/2025

Baseball Game

What is this problem about?

The "Baseball Game interview question" is a simulation challenge that involves tracking a running score based on a sequence of strings. Each string in the sequence represents either a new score, an operation to modify previous scores, or an instruction to remove the last score. This problem mimics how a scorecard might be updated in real-time during a sports event.

Why is this asked in interviews?

Companies like Microsoft and Turing use the "Baseball Game coding problem" to test a candidate's ability to manage data using a linear structure. It specifically evaluates if a candidate can correctly implement "Stack interview pattern" logic, as the operations (canceling the last score or doubling the previous one) rely on "Last-In, First-Out" (LIFO) behavior.

Algorithmic pattern used

The Stack pattern is the most efficient way to solve this.

  1. Integer: Push the value onto the stack.
  2. "+" (Sum): Look at the top two elements of the stack, add them together, and push the result.
  3. "D" (Double): Look at the top element, multiply it by 2, and push the result.
  4. "C" (Cancel): Pop the top element from the stack. Finally, sum all the elements remaining in the stack to get the total score.

Example explanation

Operations: ["5", "2", "C", "D", "+"]

  1. "5": Stack = [5]
  2. "2": Stack = [5, 2]
  3. "C": Pop the 2. Stack = [5]
  4. "D": Double the 5. Stack = [5, 10]
  5. "+": Sum 5 and 10. Stack = [5, 10, 15] Total Score: 5+10+15=305 + 10 + 15 = 30.

Common mistakes candidates make

  • Invalid Stack Access: Trying to perform "+" or "D" when there aren't enough elements in the stack (though most problem constraints guarantee valid operations).
  • String vs Integer: Forgetting to convert the numeric strings into integers before performing math.
  • Inefficient Summing: Summing the entire stack repeatedly inside the loop instead of doing it once at the very end.

Interview preparation tip

Stack-based simulation is a common interview theme. Whenever you see a problem that requires "undoing" an action or referencing the most recent items added, your first thought should be a Stack. This is a great "Array interview pattern" warmup.

Similar Questions