Taro Logo

Baseball Game

#581 Most AskedEasy
18 views
Topics:
ArraysStacks

You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record.

You are given a list of strings operations, where operations[i] is the ith operation you must apply to the record and is one of the following:

  • An integer x.
    • Record a new score of x.
  • '+'.
    • Record a new score that is the sum of the previous two scores.
  • 'D'.
    • Record a new score that is the double of the previous score.
  • 'C'.
    • Invalidate the previous score, removing it from the record.

Return the sum of all the scores on the record after applying all the operations.

The test cases are generated such that the answer and all intermediate calculations fit in a 32-bit integer and that all operations are valid.

Example 1:

Input: ops = ["5","2","C","D","+"]
Output: 30
Explanation:
"5" - Add 5 to the record, record is now [5].
"2" - Add 2 to the record, record is now [5, 2].
"C" - Invalidate and remove the previous score, record is now [5].
"D" - Add 2 * 5 = 10 to the record, record is now [5, 10].
"+" - Add 5 + 10 = 15 to the record, record is now [5, 10, 15].
The total sum is 5 + 10 + 15 = 30.

Example 2:

Input: ops = ["5","-2","4","C","D","9","+","+"]
Output: 27
Explanation:
"5" - Add 5 to the record, record is now [5].
"-2" - Add -2 to the record, record is now [5, -2].
"4" - Add 4 to the record, record is now [5, -2, 4].
"C" - Invalidate and remove the previous score, record is now [5, -2].
"D" - Add 2 * -2 = -4 to the record, record is now [5, -2, -4].
"9" - Add 9 to the record, record is now [5, -2, -4, 9].
"+" - Add -4 + 9 = 5 to the record, record is now [5, -2, -4, 9, 5].
"+" - Add 9 + 5 = 14 to the record, record is now [5, -2, -4, 9, 5, 14].
The total sum is 5 + -2 + -4 + 9 + 5 + 14 = 27.

Example 3:

Input: ops = ["1","C"]
Output: 0
Explanation:
"1" - Add 1 to the record, record is now [1].
"C" - Invalidate and remove the previous score, record is now [].
Since the record is empty, the total sum is 0.

Constraints:

  • 1 <= operations.length <= 1000
  • operations[i] is "C", "D", "+", or a string representing an integer in the range [-3 * 104, 3 * 104].
  • For operation "+", there will always be at least two previous scores on the record.
  • For operations "C" and "D", there will always be at least one previous score on the record.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What are the possible operations I can encounter in the input array, and are there any constraints on the number of operations or their type?
  2. Can the input array be empty or null? If so, what should the function return?
  3. What is the range of values for the scores that can be recorded?
  4. If the "C" operation is encountered and there are no previous scores to invalidate, what should I do?
  5. Are the input operations guaranteed to be valid according to the game's rules?

Brute Force Solution

Approach

The brute force method to calculate the baseball game score involves simulating each round one by one. We'll process the inputs in the order they appear, keeping track of the running score and any previous round scores we need. This means we check every operation and calculate the score based on the specific rules.

Here's how the algorithm would work step-by-step:

  1. Start with a blank score sheet (total score of zero).
  2. Read the first operation from the list.
  3. If it's a number, add that number to the score sheet.
  4. If it's 'C', remove the last number you added to the score sheet and subtract it from the current total score.
  5. If it's 'D', double the last number you added to the score sheet, add that doubled value to the score sheet, and add that doubled value to the current total score.
  6. If it's '+', add the last two numbers you added to the score sheet together, add the sum to the score sheet, and add the sum to the current total score.
  7. Repeat steps 2 through 6 for each operation in the list.
  8. Once you've processed all the operations, the final score sheet value is your answer.

Code Implementation

def baseball_game_brute_force(operations):
    score_sheet = []
    total_score = 0

    for operation in operations:
        if operation.isdigit() or operation.startswith('-'):
            round_score = int(operation)
            score_sheet.append(round_score)
            total_score += round_score

        elif operation == 'C':
            # Invalidate the previous score.
            last_score = score_sheet.pop()
            total_score -= last_score

        elif operation == 'D':
            # Double the previous score.
            last_score = score_sheet[-1]
            doubled_score = 2 * last_score
            score_sheet.append(doubled_score)
            total_score += doubled_score

        elif operation == '+':
            # Sum the last two scores.
            sum_of_last_two = score_sheet[-1] + score_sheet[-2]
            score_sheet.append(sum_of_last_two)
            total_score += sum_of_last_two

    return total_score

Big(O) Analysis

Time Complexity
O(n)The provided brute force solution iterates through each of the n operations in the input list once. Inside the loop, each operation ('C', 'D', '+', or a number) takes constant time to process. Therefore, the time complexity is directly proportional to the number of operations in the input list, resulting in O(n) time complexity.
Space Complexity
O(N)The provided solution uses a score sheet to store intermediate results of the baseball game. In the worst-case scenario, all inputs could be numbers, leading to the score sheet storing N numbers, where N is the number of operations in the input. The 'C', 'D', and '+' operations require access to previous scores stored in this score sheet. Thus, the auxiliary space used grows linearly with the input size N, approximating to O(N).

Optimal Solution

Approach

This game involves processing a series of operations to calculate a final score. The best approach is to keep track of the scores using a temporary record, and then sum the record at the end to get the overall score.

Here's how the algorithm would work step-by-step:

  1. Start with an empty record to store the valid scores.
  2. Go through each operation one by one.
  3. If the operation is a number, add it to the record as a new score.
  4. If the operation is 'C', remove the last score from the record.
  5. If the operation is 'D', double the last score in the record and add the result as a new score.
  6. If the operation is '+', add the last two scores in the record and add the result as a new score.
  7. After processing all operations, sum all the scores in the record. This sum is the total score.

Code Implementation

def baseball_game_score(operations):
    record = []
    
    for operation in operations:
        if operation.isdigit() or operation[0] == '-':
            record.append(int(operation))

        elif operation == 'C':
            # Invalidate the previous score.
            record.pop()

        elif operation == 'D':
            # Double the previous score.
            record.append(record[-1] * 2)

        elif operation == '+':
            # Sum the last two valid scores.
            record.append(record[-1] + record[-2])

    # Sum all scores to compute the total.
    total_score = sum(record)
    return total_score

Big(O) Analysis

Time Complexity
O(n)The code iterates through the input array of operations once. Each operation (number, 'C', 'D', or '+') takes constant time to process, involving either adding to a record, removing from a record, or performing simple arithmetic on the last elements of the record. Therefore, the time complexity is directly proportional to the number of operations, n, resulting in O(n) time complexity.
Space Complexity
O(N)The algorithm uses a record (which can be implemented as a list or stack) to store the valid scores. In the worst-case scenario, where all operations are numbers, the record will grow linearly with the number of operations N. Therefore, the auxiliary space required to store the record scales linearly with the input size N. Hence, the space complexity is O(N).

Edge Cases

Null or empty input array
How to Handle:
Return 0 immediately, as there are no scores to process.
Input array contains only 'C' operations
How to Handle:
Return 0 as all scores are canceled out.
Input array contains a sequence of '+' operations leading to integer overflow
How to Handle:
Use a data type that can handle larger sums (e.g., long) or implement overflow detection and handling.
Input array with many 'D' and '+' operations early on, leading to excessive memory usage if not managed carefully
How to Handle:
Use an efficient data structure like a stack or dynamic array for score storage.
Input array containing invalid operations (other than 'C', 'D', '+', or valid integers)
How to Handle:
Throw an exception or return an error code indicating invalid input.
Division by zero if the operations implicitly divide by zero (very unlikely, but check)
How to Handle:
Ensure that the code never executes division by zero by validating inputs before division operations.
Large number of numerical scores in the input array
How to Handle:
Ensure the chosen data structure for holding the scores is capable of handling a large number of items efficiently without performance degradation.
Input contains only extremely large positive or negative integer scores
How to Handle:
Handle potential overflow when calculating the sum of the scores.
0/1114 completed