Single-Game Tennis Scoreboard
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Implement a stateful scoreboard for a single game of tennis contested between player "A" and player "B", along with a helper function that scores an entire stream of points in order.
Tennis games follow these callout and win rules:
- Initial and regular callouts: Raw point counts
0, 1, 2, 3map to"0","15","30", and"40". Before either player wins the game or enters the Deuce zone, format the score with"A"on the left and"B"on the right as"A <a_call>-<b_call> B"(a brand-new game starts at"A 0-0 B"). - Winning the game: A player wins (
"Game A"or"Game B") the moment they reach at least4points AND lead the opponent by at least2points. - Deuce and Advantage: Once both players have won at least
3points:- Tied point totals (
3-3,4-4,5-5, ...) format as"Deuce"(never"A 40-40 B"). - A
1-point lead (4-3,5-4, ...) formats as"Advantage A"or"Advantage B". If the trailing player wins the next point, the score returns to"Deuce".
- Tied point totals (
Provide the following class and function matching starter.py:
TennisGame():- Initializes a fresh game reading
"A 0-0 B"withself.winner: Optional[str] = None(self.winnerbecomes"A"or"B"once the game finishes). point_won_by(player: str) -> str: Records one point for"A"or"B"and returns the updated score string. RaiseValueErrorwithout altering game state ifplayeris neither"A"nor"B", or ifself.winneris already set.score() -> str: Returns the current formatted score string without mutating state.
- Initializes a fresh game reading
score_sequence(points: List[str]) -> List[str]: Plays each point winner inpointsfrom a new game and returns a list containing the score string emitted after every point.
Examples
Example 1
Input:
points = ["B", "A", "A", "B", "A", "A"]
score_sequence(points)
Output:
["A 0-15 B", "A 15-15 B", "A 30-15 B", "A 30-30 B", "A 40-30 B", "Game A"]
Walk-through: "B" takes an early 0-15 lead (note "A" always stays on the left). After reaching 30-30 (2-2), "A" wins two consecutive points to reach 4-2 — at least 4 points with a 2-point margin — winning "Game A" directly from "A 40-30 B" without entering Deuce.
Example 2
Input:
points = ["A", "B", "A", "B", "A", "B", "B", "A", "A", "A"]
score_sequence(points)
Output:
[
"A 15-0 B",
"A 15-15 B",
"A 30-15 B",
"A 30-30 B",
"A 40-30 B",
"Deuce",
"Advantage B",
"Deuce",
"Advantage A",
"Game A",
]
Walk-through: The sixth point brings both players to 3-3 ("Deuce"). "B" moves ahead 3-4 ("Advantage B"), "A" equalizes at 4-4 ("Deuce"), and "A" then claims two straight points (5-4 -> "Advantage A", 6-4 -> "Game A").
Example 3
Input:
game = TennisGame()
s0 = game.score()
s1 = [game.point_won_by("B") for _ in range(4)]
w = game.winner
Output:
s0 == "A 0-0 B"
s1 == ["A 0-15 B", "A 0-30 B", "A 0-40 B", "Game B"]
w == "B"
# Calling game.point_won_by("A") now raises ValueError, while game.score() stays "Game B".
Walk-through: Four unanswered points give "B" a 4-0 shutout ("Game B"). Any subsequent point_won_by call on the finished game raises ValueError and leaves game.score() unchanged.
Constraints
0 <= len(points) <= 10^5(score_sequence([])returns[]).- Valid player identifiers are strictly uppercase
"A"and"B"; any other string raisesValueErrorwithout changing the game state. - Recording any point after a game has already been won raises
ValueErrorwithout changing the game state. TennisGame.point_won_byandTennisGame.scoremust each run inO(1)time usingO(1)memory insideTennisGame.
Step-by-step walkthrough
Understand the tennis scoring rules and format
We receive a sequence of points won by player
"A"or player"B"in a single tennis game, and after every point we must output the updated score string.Unlike sports that count
1, 2, 3, tennis uses historical callouts for the first three points won by each player:0points is"0",1point is"15",2points is"30", and3points is"40". Beyond those callouts, three special rules govern how a game ends:- Win rule: A player wins (
"Game A"or"Game B") as soon as they have at least 4 points AND lead the opponent by at least 2 points. - Deuce: Whenever both players have at least 3 points and their scores are tied (
3-3,4-4,5-5, ...), the score is called"Deuce"— never"A 40-40 B". - Advantage: Whenever both players have at least 3 points and one player leads by 1 point (
4-3,5-4, ...), the score is"Advantage A"or"Advantage B". If the trailing player wins the next point, the score returns to"Deuce".
Regular scores (0, 15, 30, 40) | +--> 4 points with >= 2-point lead (4-0, 4-1, 4-2) ----> Game A / Game B | +--> Both reach 3 points (3-3) ------------------------> Deuce / \ A scores / \ B scores v v Advantage A Advantage B / \ / \ B scores / A \ / A \ B (back to / scores \ / scores \ scores Deuce) v v v v Deuce Game A Deuce Game BBefore writing code, we also settle three interface edge cases clearly: 1. Regular scores always place A on the left and B on the right:
"A 0-15 B"means A has 0 points (0) and B has 1 point (15). 2. Before any point is played, a freshTennisGamereads"A 0-0 B". 3. Passing an unknown player name (anything other than"A"or"B") or recording a point after someone has already won is a caller mistake and raisesValueError.- Win rule: A player wins (
Store raw integer counts as the single source of truth
It is tempting to store the current score string (such as
"A 30-30 B"or"Deuce") and writeif/elifbranches to transition from one string to the next. That gets error-prone fast because display formatting becomes mixed up with game rules.Instead, keep raw integer counters (
0, 1, 2, 3, 4, ...) for each player pluswinner, and derive the display text on demand. There is only one source of truth, and checking the win rule becomes simple arithmetic. Using a dictionary keyed by"A"and"B"also makes checking whether a player name is valid a single membership test (player not in self.points).from typing import List, Optional # POINT_NAMES[k] translates raw point count k (for 0 <= k <= 3) into its tennis callout. POINT_NAMES = ["0", "15", "30", "40"] class TennisGame: def __init__(self) -> None: # self.points: dict mapping player name -> raw integer points won, e.g. {"A": 2, "B": 3} self.points = {"A": 0, "B": 0} # self.winner: "A" or "B" once the game ends, or None while play continues self.winner: Optional[str] = NoneValidate input, add a point, and check the two-part win rule
When
point_won_by(player)is called, we first validate thatplayeris"A"or"B"and that the game is not already over. Validating before changingself.pointsguarantees that a bad call never leaves the game half-updated.Next, we add
1toself.points[player]and check whetherplayerjust won. Only the player who just scored could possibly win on this turn, and they win when both parts hold:scorer_points >= 4 AND (scorer_points - opponent_points) >= 2Why do we need both conditions? -
scorer_points >= 4alone fails at4-3: after"Deuce"(3-3), a fourth point only gives"Advantage", because the lead is1. -(scorer_points - opponent_points) >= 2alone fails at2-0("A 30-0 B"): the player leads by2, but has not reached4points yet.def _opponent_of(player: str) -> str: """Return the other player's identifier ('B' for 'A', or 'A' for 'B').""" if player == "A": return "B" return "A" class TennisGame: def point_won_by(self, player: str) -> str: """Record one point for 'A' or 'B' and return the new score string.""" # Phase 1: Validate inputs BEFORE mutating state so bad calls leave the game untouched. if player not in self.points: raise ValueError(f"unknown player {player!r}; expected 'A' or 'B'") if self.winner is not None: raise ValueError(f"the game is already over: {self.score()}") # Phase 2: Increment the scorer's raw tally and check the two-part win condition. self.points[player] += 1 opponent = _opponent_of(player) scorer_points = self.points[player] opponent_points = self.points[opponent] point_lead = scorer_points - opponent_points # Both checks are required: 4-3 is only Advantage (lead < 2), and 2-0 is only 30-0 (< 4 points). if scorer_points >= 4 and point_lead >= 2: self.winner = player return self.score()Format the score string from most specific to least specific
Now
score()translates(self.winner, points_a, points_b)into a string without modifying anything. Checking the cases from most specific to least specific keeps every condition short and safe:- Game over (
self.winner is not None): return"Game A"or"Game B". - Deuce / Advantage zone (
points_a >= 3 and points_b >= 3): ifpoints_a == points_b, return"Deuce". Otherwise one player is ahead — and since nobody has won yet, their lead can only be1("Advantage A"or"Advantage B"). - Regular callouts: look up
POINT_NAMES[points_a]andPOINT_NAMES[points_b].
Why can
POINT_NAMES[points_a]never crash withIndexErrorin step 3? Supposepoints_awere4or higher. Because we already skipped step 2,points_bmust be2or lower (0,1, or2). That would meanpoints_a >= 4andpoints_a - points_b >= 2, so A would already beself.winnerand would have exited in step 1! Therefore, whenever execution reaches step 3, bothpoints_aandpoints_bare guaranteed to be in0..3.def score(self) -> str: """Return the current score string without changing the game.""" # Priority 1: Once a winner is recorded, the game stays in its terminal "Game X" state. if self.winner is not None: return "Game " + self.winner points_a = self.points["A"] points_b = self.points["B"] # Priority 2: Once both players reach at least 3 points (40-40 onward), only ties and 1-point leads exist. if points_a >= 3 and points_b >= 3: if points_a == points_b: return "Deuce" if points_a > points_b: return "Advantage A" return "Advantage B" # Priority 3: Regular score. Neither count can exceed 3 here because >= 4 against <= 2 # already has a lead >= 2 and would have set self.winner above. name_a = POINT_NAMES[points_a] name_b = POINT_NAMES[points_b] return f"A {name_a}-{name_b} B"- Game over (
Feed a stream of points through the tracker
With
TennisGamehandling one point at a time,score_sequence(points)is a straightforward loop that creates a fresh game, feeds each point in order, and collects the resulting score strings. Separating the statefulTennisGameobject from the batch helper means the exact same class also works if points arrive one by one over a live network stream.def score_sequence(points: List[str]) -> List[str]: """Play the points of one game in order and return the score after each point.""" game = TennisGame() # scores: list of formatted score strings after each point, e.g. ["A 0-15 B", "A 15-15 B"] scores: List[str] = [] for player in points: current_score = game.point_won_by(player) scores.append(current_score) return scoresTrace Example 1 and Example 2
First, trace Example 1 (
["B", "A", "A", "B", "A", "A"]), where"A"closes out the game directly from"A 40-30 B":Point Scorer Raw counts (A, B) Lead Active branch Output ----- ------ ----------------- ----- -------------------------------- ---------- start - (0, 0) 0 Priority 3: regular lookup A 0-0 B 1 B (0, 1) B +1 Priority 3: regular lookup A 0-15 B 2 A (1, 1) 0 Priority 3: regular lookup A 15-15 B 3 A (2, 1) A +1 Priority 3: regular lookup A 30-15 B 4 B (2, 2) 0 Priority 3: regular lookup A 30-30 B 5 A (3, 2) A +1 Priority 3: regular (A has < 4) A 40-30 B 6 A (4, 2) A +2 Win check: 4 >= 4 and 2 >= 2 Game ANow trace Example 2 (
["A", "B", "A", "B", "A", "B", "B", "A", "A", "A"]), which enters Deuce, swings to Advantage B and back to Deuce, and finishes:Points 1..5: (1,0) A 15-0 B -> (1,1) A 15-15 B -> (2,1) A 30-15 B -> (2,2) A 30-30 B -> (3,2) A 40-30 B Point 6 (B): (3, 3) -> both >= 3 and equal -> "Deuce" Point 7 (B): (3, 4) -> B has 4, but lead is 1 (no win!) -> "Advantage B" Point 8 (A): (4, 4) -> both >= 3 and equal again -> "Deuce" Point 9 (A): (5, 4) -> A has 5, but lead is 1 (no win!) -> "Advantage A" Point 10 (A): (6, 4) -> A has 6 >= 4 and lead 6 - 4 = 2 -> "Game A"Complete solution
from typing import List, Optional # POINT_NAMES[k] translates raw point count k (for 0 <= k <= 3) into its tennis callout. POINT_NAMES = ["0", "15", "30", "40"] def _opponent_of(player: str) -> str: """Return the other player's identifier ('B' for 'A', or 'A' for 'B').""" if player == "A": return "B" return "A" class TennisGame: """Score of a single tennis game between player 'A' and player 'B'. State is stored as raw integer point counts plus an optional winner string, giving one source of truth from which every display string is derived. """ def __init__(self) -> None: # self.points: dict mapping player name -> raw integer points won, e.g. {"A": 2, "B": 3} self.points = {"A": 0, "B": 0} # self.winner: "A" or "B" once the game ends, or None while play continues self.winner: Optional[str] = None def point_won_by(self, player: str) -> str: """Record one point for 'A' or 'B' and return the new score string.""" # Phase 1: Validate inputs BEFORE mutating state so bad calls leave the game untouched. if player not in self.points: raise ValueError(f"unknown player {player!r}; expected 'A' or 'B'") if self.winner is not None: raise ValueError(f"the game is already over: {self.score()}") # Phase 2: Increment the scorer's raw tally and check the two-part win condition. self.points[player] += 1 opponent = _opponent_of(player) scorer_points = self.points[player] opponent_points = self.points[opponent] point_lead = scorer_points - opponent_points # Both checks are required: 4-3 is only Advantage (lead < 2), and 2-0 is only 30-0 (< 4 points). if scorer_points >= 4 and point_lead >= 2: self.winner = player return self.score() def score(self) -> str: """Return the current score string without changing the game.""" # Priority 1: Once a winner is recorded, the game stays in its terminal "Game X" state. if self.winner is not None: return "Game " + self.winner points_a = self.points["A"] points_b = self.points["B"] # Priority 2: Once both players reach at least 3 points (40-40 onward), only ties and 1-point leads exist. if points_a >= 3 and points_b >= 3: if points_a == points_b: return "Deuce" if points_a > points_b: return "Advantage A" return "Advantage B" # Priority 3: Regular score. Neither count can exceed 3 here because >= 4 against <= 2 # already has a lead >= 2 and would have set self.winner above. name_a = POINT_NAMES[points_a] name_b = POINT_NAMES[points_b] return f"A {name_a}-{name_b} B" def score_sequence(points: List[str]) -> List[str]: """Play the points of one game in order and return the score after each point.""" game = TennisGame() # scores: list of formatted score strings after each point, e.g. ["A 0-15 B", "A 15-15 B"] scores: List[str] = [] for player in points: current_score = game.point_won_by(player) scores.append(current_score) return scores✅ Submit now — all tests should pass.
Intuition & how it works
Think of a stadium scoreboard with two plain tally counters in the back room and a display screen out front. In the back room, we ignore tennis's quirky point names and simply count raw integers (0, 1, 2, 3, 4, ...) for Player A and Player B. Out front, the score() method acts like a translator lens: it reads those two integers and prints "0", "15", "30", "40", "Deuce", "Advantage", or "Game".
A common first attempt is to store the formatted score string itself (such as "A 30-30 B" or "Deuce") and write a long chain of if/elif rules that rewrite one string into the next. That approach gets tangled fast because display text becomes the program's state, making it easy to miss transitions like "Advantage B" falling back to "Deuce" or "A 40-30 B" jumping straight to "Game A". Separating counting from formatting turns the entire win rule into a single arithmetic check: the scorer has at least 4 points AND leads by at least 2.
Walk through Example 1 (["B", "A", "A", "B", "A", "A"]):
- Start at {A: 0, B: 0} (winner = None).
- "B" scores -> {A: 0, B: 1} -> regular lookup prints "A 0-15 B" (with A kept on the left).
- "A", "A", "B" score -> {A: 1, B: 1} ("A 15-15 B"), {A: 2, B: 1} ("A 30-15 B"), {A: 2, B: 2} ("A 30-30 B").
- "A" scores twice more -> {A: 3, B: 2} ("A 40-30 B"), then {A: 4, B: 2} -> A now has 4 >= 4 points and a lead of 4 - 2 = 2 >= 2, setting winner = "A" and printing "Game A".
Complexity
- Time: O(1) per point, and O(n) for a sequence of n points. Recording one point updates one dictionary entry, compares two integers, and formats one short string — a fixed handful of operations regardless of how many points have been played. Processing
npoints runs that constant-time stepntimes. - Space: O(1) inside
TennisGame, plus O(n) for the output list ofscore_sequence. The game object itself stores only a two-key dictionary and an optional winner string, whilescore_sequenceallocates a list holding thenreturned score strings.
Edge cases
- Initial score (
0-0):score_sequenceonly outputs strings after each point, so an empty stream[]returns[], whereas callingTennisGame().score()directly on a new game returns"A 0-0 B". 40-30is not Deuce: At3-2, the leader's next point reaches4-2(at least4points and a2-point lead), winning"Game A"immediately without visiting"Advantage".- First
3-3is already"Deuce": A3-3tie prints"Deuce"(never"A 40-40 B"), and every later tie (4-4,5-5, ...) also prints"Deuce". - Lost advantage returns to
"Deuce": Going from3-4("Advantage B") to4-4returns cleanly to"Deuce", not"A 40-40 B". - Long Deuce battles: Even after 100 points (
50-50), Python integers do not overflow, andscore()checkspoints_a >= 3 and points_b >= 3before touchingPOINT_NAMES, so it never indexes out of bounds. - Invalid calls: Any player string other than
"A"or"B"(such as"C"or lowercase"a"), or any point afterwinneris already set, raisesValueErrorbefore mutating the counters.
Common mistakes
- Checking
points >= 4without checking the two-point lead: At4-3(one point after"Deuce"), the leader only has"Advantage", not the game. - Indexing
POINT_NAMES[4]after Deuce: Looking upPOINT_NAMES[points_a]before handling thepoints_a >= 3 and points_b >= 3branch crashes withIndexErroras soon as a player scores their fourth point at4-3. - Allowing points after the game ends: Without checking
self.winner is not Nonefirst, extra points can turn a finished"Game A"(4-2) into4-3("Advantage A"). - Mutating state before validating input: Incrementing
self.pointsbefore checking whether the game is over corrupts the stored counts when an exception is caught by the caller. - Putting the leader's score first: The output format fixes A on the left (
"A 0-40 B"when B leads 40 to 0), never"B 40-0 A".
Alternative approaches
- Explicit finite-state machine (a model with a fixed list of states and a lookup table showing which state each input moves to): Enumerate all
20possible tennis game states — the15regular pairs(a, b)in0..3excluding(3, 3), plusDeuce,Advantage A,Advantage B,Game A, andGame B— and transition directly without unbounded integer counters. This is great for hardware or UI protocols where every state must be listed explicitly, and our test suite uses it to cross-checkTennisGame. - Event log (append-only point history): Store the raw list of points
["B", "A", ...]and recompute the score on demand. Reading the score takes O(n) time instead of O(1), so it is slower for long streams, though it makes "undo last point" and full match replay trivial.
Follow-up questions
- How would you layer set and full-match scoring (including 6-6 tie-breaks) on top of TennisGame? Build a hierarchy of small classes where
Matchowns the currentSetandSetowns the currentTennisGame. WheneverTennisGame.winnerbecomes non-None,Setincrements that player's game count and starts a freshTennisGame; a standard set is won at6games with a2-game lead, or at6-6via a tie-break (a special deciding game counted in plain integers1, 2, 3, ...where the first player to reach7points with a2-point lead wins the set7-6). Similarly,Matchcounts completed sets and finishes as soon as a player reaches2sets (best-of-3) or3sets (best-of-5), with no two-set lead required. - What minimal change supports no-ad (sudden-death at Deuce) rules? In no-ad tennis, when the score reaches
"Deuce"(3-3), the very next point wins the game (4-3is immediately"Game"). Because our design isolates the win check in oneifstatement, we only need a constructor flagno_ad: bool = False: whenno_adisTrue, the win condition simplifies fromscorer_points >= 4 and point_lead >= 2to justscorer_points >= 4, and"Advantage"is automatically never reached. - How would you add an O(1) undo operation when an umpire logs a point for the wrong player? Maintain a stack (a last-in, first-out list where you push and pop from the end) of who won each point, such as
self.history = ["B", "A", "A"]. To undo in O(1) time, pop the last playerlast = self.history.pop(), decrementself.points[last] -= 1, and resetself.winner = None(since no point is allowed after a winning point, undoing any valid point is guaranteed to leave the game unfinished!).
Follow-up questions
- How would you layer set and full-match scoring (including 6-6 tie-breaks) on top of TennisGame?
- What minimal change supports no-ad (sudden-death at Deuce) rules?
- How would you add an O(1) undo operation when an umpire logs a point for the wrong player?
Similar questions
- Target-Sum Index Pair
- Column and Group Mean Imputation
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
More Aeonea interview questions
- Column and Group Mean Imputation Medium
- Target-Sum Index Pair Medium