We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Determine the Winner of a Bowling Game

Number: 2684

Difficulty: Easy

Paid? No

Companies: Amazon, DE Shaw


Problem Description

Given two integer arrays, player1 and player2, where each element represents the number of pins hit in a turn of a bowling game, compute each player's score according to the following rules:

  • For the iᵗʰ turn, if in either of the previous two turns (i-1 or i-2) the player hit all 10 pins, then the value for the current turn is doubled (2*xᵢ); otherwise, it remains xᵢ. Calculate the total score for each player and return:
  • 1 if player1 wins,
  • 2 if player2 wins,
  • 0 if the game is a draw.

Key Insights

  • The game is turn-based, and each turn's score might be doubled if the player achieved a perfect hit (10 pins) in either of the previous two turns.
  • It’s efficient to iterate over the turns once for each player while checking the last one or two turns when available.
  • Boundary checks for the first and second turn are necessary since there might not be two previous turns at the beginning.

Space and Time Complexity

Time Complexity: O(n) - where n is the number of turns, as each player's turns are processed in a single pass. Space Complexity: O(1) - additional storage is limited to a few variables for tracking scores and indices.


Solution

The solution involves iterating over both players' scores simultaneously (or separately). For each turn:

  1. Check if the previous one or two turns exist and if either of them had 10 pins knocked down.
  2. If so, double the current turn's pins; otherwise, use the pin count as it is.
  3. Sum these turn scores to determine the total score for each player.
  4. Finally, compare the scores and return 1 if player1’s score is higher, 2 if player2’s score is higher, or 0 if they are equal.

The primary data structures used here are arrays (or lists) for storing the pins knocked down each turn and simple integer variables for score accumulations. The algorithm is a straightforward simulation of the turn-by-turn game rules.


Code Solutions

# Calculate total score for a given player's turns
def calculate_score(turns):
    score = 0
    n = len(turns)
    for i in range(n):
        # Check if previous one or two turns contain a perfect hit (10 pins)
        if (i >= 1 and turns[i - 1] == 10) or (i >= 2 and turns[i - 2] == 10):
            score += 2 * turns[i]  # Double the score for this turn
        else:
            score += turns[i]      # Normal score
    return score

def isWinner(player1, player2):
    score1 = calculate_score(player1)
    score2 = calculate_score(player2)
    
    if score1 > score2:
        return 1
    elif score2 > score1:
        return 2
    else:
        return 0

# Example usage:
# print(isWinner([5,10,3,2], [6,5,7,3]))
← Back to All Questions