Implement a tennis score tracker
Company: Aeonea
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: This question evaluates a candidate's ability to implement stateful scoring logic and choose appropriate data structures for tracking sequential events, specifically handling tennis scoring rules such as 0/15/30/40 progression, Deuce, Advantage, and the two-point lead requirement.
Constraints
- 1 <= len(points) <= 100000
- points[i] is either 'A' or 'B'
- The sequence contains at least the points up to and including the first 'Game' result; any extra characters after 'Game' must be ignored
- Output after each processed point using exactly one of: 'A X-Y B', 'Deuce', 'Advantage A', 'Advantage B', 'Game A', 'Game B'
Examples
Input: ABBBB
Expected Output:
Input: AAAAA
Expected Output:
Input: ABABABABBB
Expected Output:
Input: BBBAAABB
Expected Output:
Input: AABABBABAA
Expected Output:
Solution
from typing import List
def tennis_score_stream(points: str) -> List[str]:
a = 0
b = 0
result: List[str] = []
score_map = {0: '0', 1: '15', 2: '30', 3: '40'}
for ch in points:
if ch == 'A':
a += 1
elif ch == 'B':
b += 1
else:
# Per constraints, input is valid. This branch won't occur.
continue
# Check game-winning condition
if (a >= 4 or b >= 4) and abs(a - b) >= 2:
result.append('Game A' if a > b else 'Game B')
break
# Deuce/Advantage region
if a >= 3 and b >= 3:
if a == b:
result.append('Deuce')
elif a == b + 1:
result.append('Advantage A')
elif b == a + 1:
result.append('Advantage B')
else:
# No output here because a two-point lead would have triggered 'Game'
pass
continue
# Normal scoring
result.append(f"A {score_map[a]}-{score_map[b]} B")
return result