Determine the Winner of a Bowling Game — Easy Problem & Solution
Two players bowl. player1[i] and player2[i] are the pins each knocked down in turn i.
- Difficulty: Easy
- Topics: Arrays, Simulation
- Asked at: Amazon, Microsoft, Accenture
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
Two players bowl. player1[i] and player2[i] are the pins each knocked down in turn i.
A turn's points are doubled if the player knocked down all 10 pins in either of the two previous turns; otherwise the points equal the pins.
Return 1 if player 1 wins, 2 if player 2 wins, and 0 on a tie.
Example 1
Input: player1 = [4,10,7,9], player2 = [6,5,2,3]
Output: 1
Explanation: Player 1 scores 4 + 10 + 14 + 18 = 46 against 16.
Example 2
Input: player1 = [3,5,7,6], player2 = [8,10,10,2]
Output: 2
Example 3
Input: player1 = [2,3], player2 = [4,1]
Output: 0
Explanation: Both total 5.
Constraints
n == player1.length == player2.length1 <= n <= 10000 <= player1[i], player2[i] <= 10
How to solve Determine the Winner of a Bowling Game
A direct simulation. For each turn, look back at most two turns for a strike; if one is there, the turn's points double.
Approach
- For each player, sweep the turns keeping a running total.
- At turn
i, double the points whenp[i-1] == 10orp[i-2] == 10(guarding the bounds). - Compare the totals and report 1, 2 or 0.
Why it works
The rule refers only to the raw pins in the previous turns, not to the doubled points, so no propagation is needed and one left-to-right pass is exact. The two players never interact, so scoring them separately is correct.
Complexity
- Time —
O(n) - Space —
O(1)
Pitfalls
- The doubling looks at the pins, not the already-doubled score of a previous turn.
- Both previous turns count, so it is an
orover two look-backs, not just the immediately preceding one. - The first two turns need bounds guards.
Reference solution
Python
from typing import List
def isWinner(player1: List[int], player2: List[int]) -> int:
def score(p: List[int]) -> int:
s = 0
for i, v in enumerate(p):
bonus = (i >= 1 and p[i - 1] == 10) or (i >= 2 and p[i - 2] == 10)
s += 2 * v if bonus else v
return s
a, b = score(player1), score(player2)
if a > b:
return 1
if b > a:
return 2
return 0JavaScript
var isWinner = function(player1, player2) {
var score = function(p) {
var s = 0;
for (var i = 0; i < p.length; i++) {
var bonus = (i >= 1 && p[i - 1] === 10) || (i >= 2 && p[i - 2] === 10);
s += bonus ? 2 * p[i] : p[i];
}
return s;
};
var a = score(player1), b = score(player2);
if (a > b) return 1;
if (b > a) return 2;
return 0;
};Also on the editorial tab: C, C#, C++, Go, Java, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.