#2660

Determine the Winner of a Bowling Game

Easy
ArraySimulationSimulationArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

This approach uses a single loop to calculate the scores for both players in one pass, checking the last two turns for each player to determine if the current score should be doubled. This is more efficient than the brute force method.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize scores for both players to 0.
  2. 2Step 2: Loop through each turn for both players.
  3. 3Step 3: For each turn, check the previous two turns to see if either hit 10 pins. If so, double the current turn's score; otherwise, use the normal score.
  4. 4Step 4: Sum the scores for both players.
  5. 5Step 5: Compare the scores and return 1 if player 1 wins, 2 if player 2 wins, or 0 if it's a draw.
solution.py26 lines
1# Full working Python code
2
3def determine_winner(player1, player2):
4    score1, score2 = 0, 0
5    n = len(player1)
6    for i in range(n):
7        if i > 1 and (player1[i-1] == 10 or player1[i-2] == 10):
8            score1 += 2 * player1[i]
9        elif i > 0 and player1[i-1] == 10:
10            score1 += 2 * player1[i]
11        else:
12            score1 += player1[i]
13
14        if i > 1 and (player2[i-1] == 10 or player2[i-2] == 10):
15            score2 += 2 * player2[i]
16        elif i > 0 and player2[i-1] == 10:
17            score2 += 2 * player2[i]
18        else:
19            score2 += player2[i]
20
21    if score1 > score2:
22        return 1
23    elif score2 > score1:
24        return 2
25    else:
26        return 0

Complexity note: The complexity is O(n) because we are only iterating through the players' scores once, checking conditions in constant time.

  • 1Understanding how previous scores affect current scores is crucial.
  • 2Simulating the game turn by turn helps clarify the scoring rules.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.