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, 3 map 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 least 4 points AND lead the opponent by at least 2 points.
  • Deuce and Advantage: Once both players have won at least 3 points:
    • 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".

Provide the following class and function matching starter.py:

  • TennisGame():
    • Initializes a fresh game reading "A 0-0 B" with self.winner: Optional[str] = None (self.winner becomes "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. Raise ValueError without altering game state if player is neither "A" nor "B", or if self.winner is already set.
    • score() -> str: Returns the current formatted score string without mutating state.
  • score_sequence(points: List[str]) -> List[str]: Plays each point winner in points from 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 raises ValueError without changing the game state.
  • Recording any point after a game has already been won raises ValueError without changing the game state.
  • TennisGame.point_won_by and TennisGame.score must each run in O(1) time using O(1) memory inside TennisGame.

Step-by-step walkthrough

  1. 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: 0 points is "0", 1 point is "15", 2 points is "30", and 3 points 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 B
    

    Before 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 fresh TennisGame reads "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 raises ValueError.

  2. 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 write if/elif branches 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 plus winner, 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] = None
    
  3. Validate input, add a point, and check the two-part win rule

    When point_won_by(player) is called, we first validate that player is "A" or "B" and that the game is not already over. Validating before changing self.points guarantees that a bad call never leaves the game half-updated.

    Next, we add 1 to self.points[player] and check whether player just 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) >= 2
    

    Why do we need both conditions? - scorer_points >= 4 alone fails at 4-3: after "Deuce" (3-3), a fourth point only gives "Advantage", because the lead is 1. - (scorer_points - opponent_points) >= 2 alone fails at 2-0 ("A 30-0 B"): the player leads by 2, but has not reached 4 points 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()
    
  4. 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:

    1. Game over (self.winner is not None): return "Game A" or "Game B".
    2. Deuce / Advantage zone (points_a >= 3 and points_b >= 3): if points_a == points_b, return "Deuce". Otherwise one player is ahead — and since nobody has won yet, their lead can only be 1 ("Advantage A" or "Advantage B").
    3. Regular callouts: look up POINT_NAMES[points_a] and POINT_NAMES[points_b].

    Why can POINT_NAMES[points_a] never crash with IndexError in step 3? Suppose points_a were 4 or higher. Because we already skipped step 2, points_b must be 2 or lower (0, 1, or 2). That would mean points_a >= 4 and points_a - points_b >= 2, so A would already be self.winner and would have exited in step 1! Therefore, whenever execution reaches step 3, both points_a and points_b are guaranteed to be in 0..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"
    
  5. Feed a stream of points through the tracker

    With TennisGame handling 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 stateful TennisGame object 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 scores
    
  6. Trace 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 A
    

    Now 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"
    
  7. 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 n points runs that constant-time step n times.
  • Space: O(1) inside TennisGame, plus O(n) for the output list of score_sequence. The game object itself stores only a two-key dictionary and an optional winner string, while score_sequence allocates a list holding the n returned score strings.

Edge cases

  • Initial score (0-0): score_sequence only outputs strings after each point, so an empty stream [] returns [], whereas calling TennisGame().score() directly on a new game returns "A 0-0 B".
  • 40-30 is not Deuce: At 3-2, the leader's next point reaches 4-2 (at least 4 points and a 2-point lead), winning "Game A" immediately without visiting "Advantage".
  • First 3-3 is already "Deuce": A 3-3 tie prints "Deuce" (never "A 40-40 B"), and every later tie (4-4, 5-5, ...) also prints "Deuce".
  • Lost advantage returns to "Deuce": Going from 3-4 ("Advantage B") to 4-4 returns cleanly to "Deuce", not "A 40-40 B".
  • Long Deuce battles: Even after 100 points (50-50), Python integers do not overflow, and score() checks points_a >= 3 and points_b >= 3 before touching POINT_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 after winner is already set, raises ValueError before mutating the counters.

Common mistakes

  • Checking points >= 4 without checking the two-point lead: At 4-3 (one point after "Deuce"), the leader only has "Advantage", not the game.
  • Indexing POINT_NAMES[4] after Deuce: Looking up POINT_NAMES[points_a] before handling the points_a >= 3 and points_b >= 3 branch crashes with IndexError as soon as a player scores their fourth point at 4-3.
  • Allowing points after the game ends: Without checking self.winner is not None first, extra points can turn a finished "Game A" (4-2) into 4-3 ("Advantage A").
  • Mutating state before validating input: Incrementing self.points before 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 20 possible tennis game states — the 15 regular pairs (a, b) in 0..3 excluding (3, 3), plus Deuce, Advantage A, Advantage B, Game A, and Game 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-check TennisGame.
  • 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 Match owns the current Set and Set owns the current TennisGame. Whenever TennisGame.winner becomes non-None, Set increments that player's game count and starts a fresh TennisGame; a standard set is won at 6 games with a 2-game lead, or at 6-6 via a tie-break (a special deciding game counted in plain integers 1, 2, 3, ... where the first player to reach 7 points with a 2-point lead wins the set 7-6). Similarly, Match counts completed sets and finishes as soon as a player reaches 2 sets (best-of-3) or 3 sets (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-3 is immediately "Game"). Because our design isolates the win check in one if statement, we only need a constructor flag no_ad: bool = False: when no_ad is True, the win condition simplifies from scorer_points >= 4 and point_lead >= 2 to just scorer_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 player last = self.history.pop(), decrement self.points[last] -= 1, and reset self.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

Similar questions

More Aeonea interview questions

All 3 Aeonea questions →