Baseball Game Visualizer & Step-by-Step Algorithm Solution

Keep score for a baseball game by processing score records, invalidations, doubling, and additions using a stack.

Category: stack | Difficulty: Easy

Tags: Stack, Array, Simulation, LeetCode 682

Baseball Game

Operations Stream
5
0
2
1
C
2
D
3
+
4
Push / Pop (Top)
(Empty Stack)
Score Record (LIFO)
100%
state
stack[]
recordCount0
currentSum0
totalOperations5
Start
1/24
Explanation

Initialize baseball score keeper with operations = ["5", "2", "C", "D", "+"].

Source Code
1function calPoints(operations: string[]): number {
2 const stack: number[] = [];
3 for (let operation of operations) {
4 if (operation === "C") {
5 stack.pop();
6 } else if (operation === "D") {
7 const value = stack[stack.length - 1] * 2;
8 stack.push(value);
9 } else if (operation === "+") {
10 const value = stack[stack.length - 1] + stack[stack.length - 2];
11 stack.push(value);
12 } else {
13 const value = Number(operation);
14 stack.push(value);
15 }
16 }
17 let total = 0;
18 for (let num of stack) total += num;
19 return total;
20}