#3238

Find the Number of Winning Players

Easy
ArrayHash TableCountingHash MapArray
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(n)

The optimal solution uses a hash map to count the occurrences of each color for each player in a single pass. This reduces the time complexity significantly by avoiding nested loops.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a hash map to count colors for each player.
  2. 2Step 2: Iterate through the pick array and populate the hash map with counts of each color for each player.
  3. 3Step 3: For each player, check if any color count exceeds the player's index + 1.
  4. 4Step 4: Count the number of players who meet the winning condition.
  5. 5Step 5: Return the total number of winning players.
solution.py10 lines
1# Full working Python code
2
3def count_winning_players(n, pick):
4    color_count = [{} for _ in range(n)]
5    for x, y in pick:
6        color_count[x][y] = color_count[x].get(y, 0) + 1
7    return sum(1 for player in range(n) if any(count > player for count in color_count[player].values()))
8
9# Example usage
10print(count_winning_players(4, [[0,0],[1,0],[1,0],[2,1],[2,1],[2,0]]))

Complexity note: The time complexity is O(n) because we only iterate through the picks once to build the color counts, and then we check each player's counts in linear time. The space complexity is O(n) due to the storage of color counts for each player.

  • 1Players win by collecting a specific number of balls of the same color.
  • 2Using hash maps allows efficient counting of occurrences.

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