662/670

662. Find Players With Zero or One Losses

Medium

A tournament's results arrive as matches, where each entry matches[i] = [winner_i, loser_i] records one game: the first player beat the second. Players are labeled with positive integers, and a player counts as part of the tournament only if they show up in at least one match.

Build two lists from the results:

  • every player who lost no matches at all,
  • every player who lost exactly one match.

Return the pair [zeroLosses, oneLoss], with each list sorted in increasing order (that canonical order is what the judge compares).

Example 1:

Input: matches = [[1,3],[2,3],[3,6],[5,6],[5,7],[4,5],[4,8],[4,9],[10,4],[10,9]]

Output: [[1, 2, 10], [4, 5, 7, 8]]

Explanation: Players 1, 2 and 10 appear only as winners. Players 4, 5, 7 and 8 each show up on the losing side exactly once. Players 3, 6 and 9 lost twice, so they belong to neither list.

Example 2:

Input: matches = [[2,3],[1,3],[5,4],[6,4]]

Output: [[1, 2, 5, 6], []]

Explanation: Players 1, 2, 5 and 6 never lost. Players 3 and 4 both lost twice, so the one-loss list is empty.

Constraints:

  • 1 ≤ matches.length ≤ 10⁵
  • 1 ≤ winner_i, loser_i ≤ 10⁵
  • winner_i ≠ loser_i
  • All matches[i] are distinct

Hints:

The winner of a match tells you a player exists; the loser tells you both that they exist and that their loss count went up. What single piece of information per player decides both output lists?

Keep one hash map: player → number of losses, making sure winners are inserted with zero when first seen. One pass fills it; then players with count 0 go in the first list and count 1 in the second, each sorted before returning.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: matches = [[1,3],[2,3],[3,6],[5,6],[5,7],[4,5],[4,8],[4,9],[10,4],[10,9]]

Expected output: [[1, 2, 10], [4, 5, 7, 8]]