← Microsoft bank

Microsoft · Question 33 · Stacks

Baseball Game

StacksJavacode⏱ O(n)💾 O(n)
Product-based

Problem

You are given a list of operations that represent scores. Implement rules for '+', 'D', and 'C'. Return the total score.

Approach

Replay operations on a stack: C voids, D doubles, + sums the top two.

Time O(n)Space O(n)

How it works

  1. 1Numbers push directly.
  2. 2C/D/+ rewrite the stack top accordingly.
  3. 3Sum the surviving records.

Sample input / output

Input:
5
5 2 C D +
Output:
30

Constraints

1 <= ops.length <= 1000; valid operations guaranteed.

Solution — read it, then walk it

Time O(n)Space O(n)Loops 3Branches 3Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step.
yesnoyesnoyesno↻ repeat↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE static intcalPoints(String[] ops)Stack<Integer> stack = newStack<>()for (String op : ops)if (op.equals("C"))stack.pop()else if(op.equals("D")) {stack.push(2 *stack.peek())else if(op.equals("+")) {DEFINE top = stack.pop()DEFINE newTop = top +stack.peek()stack.push(top)stack.push(newTop)} elseDEFINE sum = 0for (int score :stack)sum += scoreRETURN sumDEFINE static voidmain(String[] args)java.util.Scanner sc = newjava.util.Scanner(System.in)DEFINE ops = sc.nextInt()String[] tokens = newString[ops]for (int i = 0; i <ops; i++) tokens[i] =sc.next()System.out.println(calPoints(tokens))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/26

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits