Live Scoreboard Engine for One Tennis Game
Data Structure DesignModel answerLast updated
Process a sequence of point winners for a single tennis game and print the correct score after each point, including deuce, advantage and the win-by-two rule.
You are writing the scoring engine behind a live tennis scoreboard. It covers one game, which is played one point at a time. Each point is won by player A or player B.
Input: an ordered sequence of symbols, each 'A' or 'B', giving the winner of each point.
Output: one line after every point, describing the game at that moment.
Scoring rules:
- A player's score goes 0, 15, 30, 40 as they win their first, second and third point.
- If both players have at least three points and are level, show
Deuce. Never show40-40. - If both players have at least three points and one is exactly one point ahead, show
Advantage AorAdvantage B. - A player wins the game by winning at least four points and leading by at least two. Show
Game AorGame B. - Otherwise show
A <score>-<score> B, for exampleA 30-15 B.
Example. The sequence A, B, B, B, B produces:
A 15-0 B
A 15-15 B
A 15-30 B
A 15-40 B
Game B
What to deliver:
- Explain what state you store and how each point updates it.
- Implement the engine in the language of your choice.
- State your policy for invalid input: a point after the game is already decided, or a symbol other than
'A'or'B'. - Give the outputs for the example above and for at least one sequence that passes through deuce.
- State the time and space complexity.
Hints
Hint 1
Don't make the printed labels (`15`, `Deuce`, `Adv`) your state. Ask what is the smallest piece of numeric information that fully determines the score.
Hint 2
Track how many points each player has won. The display is then a pure function of those two numbers. Test the conditions in order: game over, then deuce/advantage, then the plain 0/15/30/40 lookup.
Hint 3
Once both players have at least 3 points and the game isn't over, they can only be level or one apart, so long deuce battles need no extra state. Don't forget to reject points that arrive after the game has ended.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Pin down the contract first
Before writing code I would settle these points:
- Input: an iterable of
'A'/'B', one per point. - Output: one string per point, one of
A 30-15 B,Deuce,Advantage A,Advantage B,Game A,Game B. - Scope: a single game. A point after the game is decided, or any symbol other than uppercase
'A'/'B', raisesValueError. - Empty input: returns an empty list.
Core design: keep counts, compute the label
A tempting first design is a state machine whose states are the labels (15-30, Deuce, Adv A, ...) with a transition table. It works, but the deuce/advantage loop produces many special cases and is easy to get wrong.
A simpler design stores only two integers, a and b, the number of points each player has won. Every label is a pure function of (a, b), so an update is just "increment one counter, recompute the label".
The label function checks, in this order:
- Game won:
max(a, b) >= 4andabs(a - b) >= 2. The leader wins. - Deuce / Advantage:
a >= 3andb >= 3. Equal counts giveDeuce. A gap of one givesAdvantageto the leader. - Plain score: map each count through
["0", "15", "30", "40"]and printA x-y B.
State needed: two integers, one constant lookup list, and a flag that records the game has ended.
Why the branches cover every reachable state
- If branch 1 fails and both counts are at least 3, the gap must be 0 or 1. A gap of 2 or more would mean the leader has at least 5 points and a two-point lead, which is a win. So branch 2 needs no extra checks, and it handles arbitrarily long deuce rallies (7-6, 12-11, and so on) with no extra state.
- If branches 1 and 2 both fail, at least one player has fewer than 3 points. The opponent can't have 4 or more, because that would be a lead of at least 2, which is a win. So both counts are in 0..3 and the lookup can't go out of range.
- 3-3 falls into branch 2 and is shown as
Deuce, matching the convention that40-40is never printed.
Worked examples
The given example:
| Point | Counts (A, B) | Output |
|---|---|---|
| A | 1, 0 | A 15-0 B |
| B | 1, 1 | A 15-15 B |
| B | 1, 2 | A 15-30 B |
| B | 1, 3 | A 15-40 B |
| B | 1, 4 | Game B |
A sequence through deuce, A A A B B B A B B:
A 15-0 B, A 30-0 B, A 40-0 B, A 40-15 B, A 40-30 B, Deuce, Advantage A, Deuce, Advantage B.
One more B would then give Game B.
Implementation (Python)
from typing import Iterable, List
NAMES = ["0", "15", "30", "40"]
def render(a: int, b: int) -> str:
"""Display string for raw point counts a (player A) and b (player B)."""
leader = "A" if a > b else "B"
if max(a, b) >= 4 and abs(a - b) >= 2:
return f"Game {leader}"
if a >= 3 and b >= 3:
return "Deuce" if a == b else f"Advantage {leader}"
return f"A {NAMES[a]}-{NAMES[b]} B"
class Scoreboard:
def __init__(self) -> None:
self.a = 0
self.b = 0
self.over = False
def record(self, winner: str) -> str:
if self.over:
raise ValueError("Game is already over")
if winner == "A":
self.a += 1
elif winner == "B":
self.b += 1
else:
raise ValueError(f"Invalid player: {winner!r}")
text = render(self.a, self.b)
self.over = text.startswith("Game")
return text
def run_game(points: Iterable[str]) -> List[str]:
board = Scoreboard()
return [board.record(p) for p in points]
Note that render is a pure function, so the full rule table can be unit-tested without involving any state.
Complexity
- Time: O(1) per point, O(n) for n points.
- Space: O(1) for the tracker. Returning every output line costs O(n). A generator version stays at O(1).
Edge cases to test
- Love game:
A A A Agives15-0,30-0,40-0,Game A. - Reaching 3-3: prints
Deuce, not40-40. - Losing the advantage: Advantage A followed by a point for B goes back to
Deuce. - Winning from 40-30: at 3-2 the leader wins the next point, making it 4-2. That is a game because the lead is 2.
- Only a one-point lead at 4: 4-3 is
Advantage, not a win. - Long deuce: dozens of alternating points never break the logic.
- Point after the game: raises an error rather than silently continuing.
- Bad input: lowercase letters and other symbols are rejected unless you explicitly choose to normalise them.
Common mistakes and trade-offs
- Storing labels instead of counts, which leads to a large transition table and bugs around advantage and deuce.
- Declaring the game at 4-3 and forgetting the two-point margin.
- Testing deuce before game over, which misreports states like 5-3.
- Printing
40-40instead ofDeuce. - Mixing scoring rules with I/O, which makes the logic hard to test.
Extensions worth mentioning
- Tiebreak: first to 7 with a two-point lead, using the same counters but printing raw numbers.
- No-ad scoring: at deuce the next point wins the game, a one-line change to the win condition.
- Sets and matches: wrap the game tracker in a higher-level tracker that counts games, then sets.
- Streaming API: expose
recordthrough a generator or callback for a live feed.