Problem 3175

Abstract / Summary

Find the earliest player who wins k consecutive games in a sequence of game results.

Note

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

Python 3175.py

class Solution:
    def findWinningPlayer(self, skills: List[int], k: int) -> int:
        # there can only be one ...
        if k >= len(skills):
            return skills.index(max(skills))

        # edge case: first game decides
        if k == 1:
            return 0 if skills[0] > skills[1] else 1

        # brute force
        result = 0
        best   = skills[0]
        streak = 0
        for i, s in enumerate(skills[1 :], 1):
            if best < s:
                best   = s
                result = i
                streak = 1
            else:
                streak += 1
                if streak == k:
                    break

        return result
25 lines | 699 bytes | submitted July 6, 2024 | GitHub   15% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 40% (90k+ 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 Solution class implements a method findWinningPlayer that determines which player wins a sequential competition based on their skill levels. The algorithm processes the skills list while respecting a parameter k that limits how many consecutive defeats a player can endure before the competition stops. The implementation is concise, handling several special conditions up front and then iterating through the remaining players with an early-exit strategy.

Key Steps

The method can be broken down into distinct logical sections, each reflected by a code fragment.

Handling the case where k exceeds the number of participants

if k >= len(skills):
    return skills.index(max(skills))

When k is larger than or equal to the total number of players, the competition can never be halted by a streak of defeats. In this scenario the winner is simply the player with the highest skill value. The code uses max to locate the maximum skill and index to return the first occurrence, guaranteeing a deterministic result even when multiple players share the top skill.

Immediate decision when only one defeat is allowed

if k == 1:
    return 0 if skills[0] > skills[1] else 1

If k equals one, the competition ends after the first loss. The method therefore compares the first two players directly and returns the index of the stronger one. This avoids any unnecessary traversal of the list.

Main iteration with streak tracking

result = 0
best   = skills[0]
streak = 0
for i, s in enumerate(skills[1 :], 1):
    if best < s:
        best   = s
        result = i
        streak = 1
    else:
        streak += 1
        if streak == k:
            break

The loop starts from the second player (index 1) and maintains three variables:

  • best - the highest skill encountered so far.
  • result - the index of the player who currently holds the lead.
  • streak - the count of consecutive players who did not surpass best.

When a player with a higher skill appears, best and result are updated, and the streak resets to one because the new leader has just defeated the previous one. If a player does not exceed best, the streak increments. Once the streak reaches k, the loop terminates because the competition rule dictates that k consecutive defeats end the game.

Returning the final winner

return result

After the loop either completes naturally or breaks early, the method returns the stored result, which corresponds to the index of the winning player.

Edge Cases Handled

The implementation explicitly addresses several boundary conditions:

  • k larger than the participant count - The early return ensures the function does not attempt to iterate beyond the list bounds and correctly identifies the strongest player.
  • Only two participants with k == 1 - By directly comparing the first two skills, the method avoids unnecessary work and correctly resolves the winner when the competition ends after a single loss.
  • Multiple players sharing the maximum skill - The use of list.index returns the first occurrence, providing a consistent tie-breaking rule without extra logic.
  • Immediate streak termination - The loop’s break condition guarantees that as soon as k consecutive non-leading players appear, the algorithm stops, respecting the competition’s stop condition.

Performance Optimizations

The code incorporates several techniques that reduce unnecessary computation:

  • Early exits for extreme k values - By handling k >= len(skills) and k == 1 before any iteration, the method avoids traversing the list when the outcome can be determined instantly.
  • Single pass through the list - The main loop processes each player at most once, updating state variables in constant time per iteration.
  • Minimal state tracking - Only three scalar variables (best, result, streak) are maintained, eliminating the need for auxiliary data structures.
  • Break on streak completion - The loop terminates as soon as the required streak length is reached, preventing further unnecessary checks once the winner is known.

These choices collectively ensure that the function operates efficiently across a wide range of input sizes and parameter values.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a long line of children wanting to play a game. Each child has a special number called a skill level written on their shirt. The person with the higher number on their shirt always wins the round.

The code starts by looking at everyone in the line. If the number of wins needed is bigger than the number of people, the person with the very highest skill number instantly wins because nobody can ever beat them.

When the game starts, you pick two people to face off. The winner stays at the front of the line to play again, and the loser goes to the back. A player needs to win a specific amount of games in a row to be declared the champion.

The computer keeps track of who is currently winning by remembering the best skill number it has seen so far. It also keeps a counter for how many times that person has won in a row. As the computer watches each new person step up to play, it compares their skill number to the one currently winning. If the new person is stronger, they become the new champion and their streak starts at one. If the current winner stays strong, their streak increases by one. The process keeps moving forward until someone reaches the goal number of wins.

written by google gemini

Code Quality

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

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 Python C++ TS
WalkCCC Java Python C++
leetcode.ca Java Python C++ Go TS
Progiez Java Python C++
github charles-wangkai Java
fsq Python
varunu28 Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
Progiez C++, Java, Python
charles-wangkai Java
fsq Python
varunu28 Java
18 links | 7 authors | 5 languages

Videos

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

Solved On The Same Day

2 solutions   July 6, 2024

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