Problem 2660

Abstract / Summary

Two players roll bowling balls alternately and the one with the highest total score after all rolls wins.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 2660.py

class Solution:
    def isWinner(self, player1: List[int], player2: List[int]) -> int:
        def score(turns):
            result = 0
            for i, t in enumerate(turns):
                result += t
                if   i >= 1 and turns[i - 1] == 10:
                    result += t
                elif i >= 2 and turns[i - 2] == 10:
                    result += t
            return result

        one = score(player1)
        two = score(player2)
        if one > two:
            return 1
        if one < two:
            return 2
        return 0
19 lines | 581 bytes | submitted October 11, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 38% (100k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Simulation
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class with a single public method isWinner. This method receives two integer lists representing the scores of two players in a turn-based game. The core of the logic resides in a nested helper function score that computes the total points for a given sequence of turns, applying a bonus rule when a turn scores exactly ten. After both totals are obtained, the method returns 1 if the first player wins, 2 if the second player wins, or 0 for a tie.

Key Steps

Definition of the public interface

class Solution:
    def isWinner(self, player1: List[int], player2: List[int]) -> int:

The method signature declares the expected input types and the integer result that indicates the winner.

Local scoring function

def score(turns):
    result = 0
    for i, t in enumerate(turns):
        result += t
        if   i >= 1 and turns[i - 1] == 10:
            result += t
        elif i >= 2 and turns[i - 2] == 10:
            result += t
    return result

The helper iterates over the turn list while maintaining a running total result. For each turn t, the base value is added. Two conditional branches check whether the previous turn (i-1) or the turn before that (i-2) was a perfect score of ten. If either condition holds, the current turn’s value is added again, thereby granting a bonus.

Computing each player’s total

one = score(player1)
two = score(player2)

The helper is invoked separately for the two input lists, producing two independent totals.

Determining the outcome

if one > two:
    return 1
if one < two:
    return 2
return 0

A straightforward comparison yields the appropriate return value: 1 for a first-player victory, 2 for a second-player victory, and 0 when the scores are equal.

Edge Cases Handled

When the turn list is empty, the for loop never executes, leaving result at its initial value of zero. Consequently, both players receive a score of zero and the method returns 0, correctly representing a tie.

If the list contains a single element, the conditional checks i >= 1 and i >= 2 both evaluate to false, so no bonus is applied. The method therefore returns the raw value of that single turn, which aligns with the intended scoring rules.

When a perfect-score turn appears at the second position (i == 1), the first conditional (i >= 1 and turns[i - 1] == 10) becomes true for the following turn, granting the appropriate bonus. Similarly, a perfect score at the third position (i == 2) triggers the second conditional (i >= 2 and turns[i - 2] == 10) for the current turn, ensuring that a bonus is awarded even when the perfect turn is two steps behind.

Consecutive perfect scores are also accommodated. For a sequence like [10, 10, 5], the first 10 contributes its base value. The second 10 receives a bonus from the preceding perfect score, and the 5 receives a bonus from the immediate previous perfect score as well as from the perfect score two steps earlier, because both conditionals are evaluated in order and the first matching branch applies the bonus once per turn.

Performance Optimizations

The scoring routine processes each turn exactly once, using a single loop that updates a local accumulator. By referencing the original list directly (turns[i - 1] and turns[i - 2]) rather than constructing auxiliary data structures, the implementation avoids additional memory allocation. The use of enumerate provides both the index and the turn value without extra lookups, keeping the inner loop body minimal. The early if … elif chain ensures that at most one bonus addition occurs per iteration, preventing redundant calculations. Overall, the design achieves a tight, linear traversal with constant auxiliary space.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a bowling game where two friends are each taking turns to knock down pins. The computer keeps track of how many pins each friend hits by looking at a list of their shots.

There is a special rule for this game. If a player hits ten pins on a turn, they get a bonus because they were super good at bowling. To give them the bonus, the game looks backwards at the last two turns. If the player hit ten pins in either of those recent turns, the points for their current turn are doubled.

The code defines a helper mission called score that calculates the total points for one person. It walks through every turn one by one, adding up the pins. If it sees that a player had a lucky ten on one of the turns just before the current one, it adds those points again as a reward.

After calculating the final total for the first friend and the second friend, the code compares the totals. It checks which number is bigger to see who finished with the most points, just like a referee watching a scoreboard to decide who wins.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 7.15 | σ = 0.99

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster Java C++ Python TS
WalkCCC Java C++ Python
leetcode.ca Java Rust C++ Go Python TS
Progiez Java C++ Python
github charles-wangkai Java
everthis JS
fsq Rust
varunu28 Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
charles-wangkai Java
everthis JavaScript
fsq Rust
varunu28 Java
20 links | 8 authors | 7 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

16 solutions   October 11, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality