Find Players With Zero or One Losses - Problem

You are given an integer array matches where matches[i] = [winneri, loseri] indicates that the player winneri defeated player loseri in a match.

Return a list answer of size 2 where:

  • answer[0] is a list of all players that have not lost any matches.
  • answer[1] is a list of all players that have lost exactly one match.

The values in the two lists should be returned in increasing order.

Note:

  • You should only consider the players that have played at least one match.
  • The testcases will be generated such that no two matches will have the same outcome.

Input & Output

Example 1 — Basic Tournament
$ 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,6,7,8]]
💡 Note: Players 1, 2, 10 never lost (0 losses). Players 4, 5, 6, 7, 8 lost exactly once. Player 3 lost twice (excluded), player 9 lost twice (excluded).
Example 2 — Simple Case
$ Input: matches = [[2,3],[1,3],[3,4]]
Output: [[1,2],[4]]
💡 Note: Players 1 and 2 never lost. Player 4 lost exactly once. Player 3 lost twice (excluded from both lists).
Example 3 — Single Match
$ Input: matches = [[1,2]]
Output: [[1],[2]]
💡 Note: Player 1 won and never lost (0 losses). Player 2 lost exactly once.

Constraints

  • 1 ≤ matches.length ≤ 105
  • matches[i].length == 2
  • 1 ≤ winneri, loseri ≤ 105
  • winneri ≠ loseri
  • All matches[i] are unique

Visualization

Tap to expand
Find Players With Zero or One Losses INPUT matches array (winner, loser) [1, 3] [2, 3] [3, 6] [5, 6] [5, 7] [4, 5] [4, 8] [4, 9] [10, 4] [10, 9] Player Network 1 2 3 4 10 5 6 7 8 9 0 losses 1 loss 2+ losses ALGORITHM STEPS 1 Create Loss Count Map Track losses for each player 2 Process Each Match Add winner if new, increment loser lossCount HashMap Player: 1 2 3 4 5 Losses: 0 0 2 1 1 Player: 6 7 8 9 10 Losses: 1 1 1 2 0 0 losses: 1, 2, 10 1 loss: 4, 5, 6, 7, 8 3 Filter Results Separate 0-loss and 1-loss 4 Sort Both Lists Return in increasing order FINAL RESULT answer[0]: Zero Losses 1 2 10 [1, 2, 10] answer[1]: Exactly One Loss 4 5 6 [4, 5, 6, 7, 8] OUTPUT: [[1,2,10], [4,5,6,7,8]] Key Insight: Use a HashMap to track loss counts: winners with 0 entries = never lost, players with exactly 1 = one loss. Time: O(n log n) for sorting | Space: O(n) for the hash map storing all unique players. TutorialsPoint - Find Players With Zero or One Losses | Hash Map Approach
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
83.3K Views
Medium Frequency
~15 min Avg. Time
2.3K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen