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 listanswer
of size2
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.
Examples
Example 1
|
|
Example 2
|
|
Constraints
1 <= matches.length <= 10^5
matches[i].length == 2
1 <= winneri, loseri <= 10^5
winneri != loseri
- All
matches[i]
are unique.
Solution
Method 1 – Counting Losses with Hash Map
Intuition
We count the number of losses for each player using a hash map. Players with zero losses are those who never appear as a loser, and players with exactly one loss appear once as a loser. We only consider players who played at least one match.
Approach
- Initialize a hash map to count losses for each player.
- For each match, increment the loss count for the loser and ensure the winner is in the map (with 0 losses if not present).
- Iterate through the map:
- Add players with 0 losses to the first list.
- Add players with 1 loss to the second list.
- Sort both lists and return them as the answer.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n log n)
, wheren
is the number of unique players, due to sorting. - 🧺 Space complexity:
O(n)
, for the loss map and answer arrays.