Find Players With Zero or One Losses (LeetCode 2225): Solution and Explanation

Medium
Array
Hash table
Sorting
Counting

Each match is a pair [winner, loser]. Return two sorted lists: the players who never lost a match, and the players who lost exactly one. Players who never appear in any match are ignored.

Intuition

The only fact that decides where a player goes is how many matches they lost. Wins do not matter for the answer, except for one detail: a player who only ever won still has to be found, so they need to be recorded somewhere.

That points to a loss ledger. Read the matches once. For the loser, add one to their count. For the winner, create an entry with zero losses if they are not there yet, and otherwise leave them alone. After the pass, every player who played has an entry with their exact number of losses.

The output must be sorted, so visit the players in increasing id order. A count of 0 goes into the first list, a count of 1 into the second, and anything higher is skipped. Because the visit order is already sorted, both lists come out sorted without any extra work.

Approach: Loss counting with a hash map

  1. Create an empty map losses from player to number of losses.
  2. For each match [w, l]: if w is not in the map, set losses[w] = 0. Then add 1 to losses[l].
  3. Create two empty lists, zero and one.
  4. Visit the players in increasing order. Append a player to zero if their count is 0, to one if it is 1, and skip them otherwise.
  5. Return [zero, one].

Step-by-step example

matches = [[1,3],[2,3],[3,6],[5,6],[5,7],[4,5],[4,8],[4,9],[10,4],[10,9]]
  1. [1,3] and [2,3]: players 1 and 2 enter with 0 losses, and player 3 reaches 2 losses.
  2. [3,6] and [5,6]: player 3 is already known, player 5 enters with 0, and player 6 reaches 2 losses.
  3. [5,7], [4,5], [4,8], [4,9]: player 7 gets 1 loss, player 4 enters with 0, player 5 now has 1, players 8 and 9 have 1 each.
  4. [10,4] and [10,9]: player 10 enters with 0, player 4 now has 1 and player 9 reaches 2.
  5. Sorted scan: 1 (0), 2 (0), 3 (2), 4 (1), 5 (1), 6 (2), 7 (1), 8 (1), 9 (2), 10 (0).
  6. The result is [[1,2,10],[4,5,7,8]].

Code: Python, Java, C++

1class Solution:
2    def findWinners(self, matches: List[List[int]]) -> List[List[int]]:
3        losses = {}
4        for winner, loser in matches:
5            losses.setdefault(winner, 0)
6            losses[loser] = losses.get(loser, 0) + 1
7        zero, one = [], []
8        for p in sorted(losses):
9            if losses[p] == 0:
10                zero.append(p)
11            elif losses[p] == 1:
12                one.append(p)
13        return [zero, one]
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(m + p log p)

Reading the m matches is linear, and sorting the p distinct players costs p log p. With an array indexed by id the sort disappears and the time is O(m + maxId).

Space

O(p)

The map holds one entry per distinct player.

Other approaches

Counting array indexed by player id (time O(m + maxId), space O(maxId))

Ids are at most 100,000, so use an array of that size filled with -1 for players who never played. Set winners to 0 if they are still -1 and increment losers. Scanning the array from 1 upward gives sorted output directly.

Two sets (time O(m + p log p), space O(p))

Keep a set of all players and a map of loss counts, then filter the set. It is the same idea with a separate structure for players who played, which some find easier to read.

Common mistakes

  • Counting only losers. Players who never lost would never enter the map and the first list would always be empty.
  • Resetting a winner's count to 0 every time they win, which erases losses they already had.
  • Returning the lists in map iteration order. Hash maps in most languages do not keep keys sorted.
  • Including players with zero matches when using a counting array. Use a sentinel such as -1 to tell them apart from unbeaten players.

Frequently asked questions

Why do winners need an entry in the map?

The first list is made of players who never lost. Those players only ever appear as winners, so if winners are not recorded the algorithm has no way to know they exist.

Can a player appear in both lists?

No. Each player has exactly one loss count, and a count cannot be both 0 and 1.

Is a TreeMap better than a HashMap here?

A TreeMap keeps keys sorted, so the final scan needs no separate sort. A HashMap plus one sort at the end has the same overall complexity, and either is fine in an interview.