oneby7

Stacks and Queues Matching and cancelling

199. Baseball Game

Easy

You are keeping the score of a game with unusual rules. A record of scores starts empty, and you are given a list of strings operations, applied to it in order. Each operation is one of these:

  • An integer x, such as "7" or "-3": add a new score of x to the record.
  • "+": add a new score equal to the sum of the two most recent scores in the record.
  • "D": add a new score equal to twice the most recent score in the record.
  • "C": cancel the most recent score in the record, removing it.

A cancelled score is gone for good, so later operations never see it. Return the sum of the scores left in the record after the last operation.

Example 1

Input: operations = ["3", "8", "+", "D", "C", "-4", "+"]

Output: 25

Explanation: The record grows to [3, 8, 11, 22]. "C" removes 22, and "-4" adds −4. The last "+" adds 11 + (−4) = 7. The record ends as [3, 8, 11, −4, 7], which sums to 25.

Example 2

Input: operations = ["-6", "D", "+", "C", "C"]

Output: -6

Explanation: The record grows to [−6, −12, −18]. The two cancels remove −18 and then −12, so only −6 is left.

Example 3

Input: operations = ["1000000000", "1000000000", "+", "D"]

Output: 8000000000

Explanation: The record ends as 109, 109, 2 × 109 and 4 × 109.

Check your understanding

Work out the answer for this input before you write any code.

operations = ["2", "3", "+", "C", "D"]

Constraints

  • 1 ≤ operations.length ≤ 105
  • Each operations[i] is "+", "D", "C" or an integer from -109 to 109, written in decimal with no leading zeros
  • A "+" comes only when the record holds at least two scores, and a "D" or "C" only when it holds at least one
  • Every score added to the record is between -1010 and 1010

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.