682. Baseball Game
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to simulate a baseball game with peculiar scoring rules and calculate the total score. We are given a sequence of operations that modify a record of scores. The operations are: adding a new score, adding a score that is the sum of the previous two, doubling the previous score, or invalidating the previous score. The key observation is that all operations involve the most recent scores. For example, 'C' invalidates the last score, 'D' doubles the last score, and '+' sums the last two scores. This "Last-In, First-Out" (LIFO) behavior strongly suggests that a stack is the most suitable data structure for managing the record of scores.
Solution
Baseball Game in Python
class Solution:
def calPoints(self, operations: List[str]) -> int:
# We use a list to simulate a stack, as it efficiently supports `append` (push) and `pop`.
record = []
# Iterate through each operation in the list.
for op in operations:
if op == '+':
# If the operation is '+': Add the sum of the last two scores to the record.
# `record[-1]` is the last score, `record[-2]` is the second to last.
# The problem guarantees at least two previous scores.
record.append(record[-1] + record[-2])
elif op == 'D':
# If the operation is 'D': Double the last score and add it to the record.
# The problem guarantees at least one previous score.
record.append(record[-1] * 2)
elif op == 'C':
# If the operation is 'C': Remove the last score from the record.
# The problem guarantees at least one previous score.
record.pop()
else:
# Otherwise, the operation is a number string. Convert it to an integer and add it.
record.append(int(op))
# After processing all operations, `sum(record)` gives the total score.
return sum(record)
Baseball Game in Java
class Solution {
public int calPoints(String[] operations) {
// Use a Stack to store the scores, as operations are based on the last valid rounds.
Stack<Integer> record = new Stack<>();
// Iterate through each operation in the input array.
for (String op : operations) {
if (op.equals("+")) {
// For '+', get the top two scores, calculate their sum, and push the result.
// Problem guarantees at least two previous scores.
int score1 = record.pop();
int score2 = record.peek();
record.push(score1); // Push the first score back
record.push(score1 + score2);
} else if (op.equals("D")) {
// For 'D', peek at the top element, double it, and push the result.
// Problem guarantees at least one previous score.
record.push(record.peek() * 2);
} else if (op.equals("C")) {
// For 'C', simply pop the top element from the stack to invalidate it.
// Problem guarantees at least one previous score.
record.pop();
} else {
// For a number, parse it to an integer and push it onto the stack.
record.push(Integer.parseInt(op));
}
}
// Finally, iterate through the stack to sum up all the scores for the total.
int sum = 0;
for (int score : record) {
sum += score;
}
return sum;
}
}
Baseball Game in C++
class Solution {
public:
int calPoints(vector<string>& operations) {
// Use a vector to act as a stack to keep track of the scores.
vector<int> record;
// Iterate through each operation.
for (const string& op : operations) {
if (op == "+") {
// For '+', get the last two scores, sum them, and push the result.
// The problem guarantees there are at least two previous scores.
int score1 = record.back();
int score2 = record[record.size() - 2];
record.push_back(score1 + score2);
} else if (op == "D") {
// For 'D', get the last score, double it, and push the result.
// The problem guarantees there is at least one previous score.
record.push_back(record.back() * 2);
} else if (op == "C") {
// For 'C', remove the last score.
// The problem guarantees there is at least one previous score.
record.pop_back();
} else {
// Otherwise, it's a number. Convert it to an integer and push it.
record.push_back(stoi(op));
}
}
// Calculate the sum of all scores in the record.
int sum = 0;
for (int score : record) {
sum += score;
}
return sum;
// A more concise way using std::accumulate:
// #include <numeric>
// return std::accumulate(record.begin(), record.end(), 0);
}
};
Baseball Game in TypeScript
function calPoints(operations: string[]): number {
// We use a number array to act as a stack to store the scores.
const record: number[] = [];
// Loop through each operation string.
for (const op of operations) {
const n = record.length;
if (op === '+') {
// Add the sum of the last two scores.
// The problem guarantees that for '+', the record will have enough elements.
record.push(record[n - 1] + record[n - 2]);
} else if (op === 'D') {
// Add the double of the last score.
// We peek at the last element (record[n-1]), double it, and push it.
record.push(record[n - 1] * 2);
} else if (op === 'C') {
// Invalidate and remove the last score. `record.pop()` does this.
record.pop();
} else {
// It's a number, parse the string to an integer and push it onto the stack.
record.push(parseInt(op, 10));
}
}
// After the loop, we sum all elements in the record.
// The `reduce` method is a concise way to do this.
return record.reduce((sum, score) => sum + score, 0);
};
More Easy LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.