#2225

Find Players With Zero or One Losses

Medium
ArrayHash TableSortingCountingHash 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)

In the optimal solution, we use a single pass through the matches to count losses for each player using a hash map. This reduces the time complexity significantly, allowing us to efficiently categorize players.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a hash map to count losses for each player.
  2. 2Step 2: Iterate through the matches and update the loss count for the loser in the hash map.
  3. 3Step 3: Create two lists for players with zero losses and one loss by checking the hash map.
solution.py8 lines
1def findWinners(matches):
2    loss_count = {}
3    for winner, loser in matches:
4        loss_count[loser] = loss_count.get(loser, 0) + 1
5        loss_count.setdefault(winner, 0)
6    zero_losses = [player for player, losses in loss_count.items() if losses == 0]
7    one_loss = [player for player, losses in loss_count.items() if losses == 1]
8    return [sorted(zero_losses), sorted(one_loss)]

Complexity note: The time complexity is O(n) because we only iterate through the matches once and then through the hash map, which is efficient for large inputs.

  • 1Using a hash map allows for efficient counting of losses without needing nested loops.
  • 2Sorting the final lists ensures the output is in increasing order, which is a common requirement.

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