Find Players With Zero or One Losses Problem
#2225
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2225.
You are given an integer array matches where matches[i] = [winner_i, loser_i] indicates that the player winner_i defeated player loser_i 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.
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 have not lost any matches.
Players 4, 5, 7, and 8 each have lost one match.
Players 3, 6, and 9 each have lost two matches.
Thus, answer[0] = [1,2,10] and answer[1] = [4,5,7,8].
Example 2:
Input: matches = [[2,3],[1,3],[5,4],[6,4]]
Output: [[1,2,5,6],[]]
Explanation:
Players 1, 2, 5, and 6 have not lost any matches.
Players 3 and 4 each have lost two matches.
Thus, answer[0] = [1,2,5,6] and answer[1] = [].
Constraints:
1 <= matches.length <= 10^5matches[i].length == 21 <= winner_i, loser_i <= 10^5winner_i != loser_i- All
matches[i]are unique.
Solution
Approach: Hash Map and Sorting
Count how many matches each player has lost in a hash map. Every winner must also be registered (with 0 losses) in case they never lose. Then collect the players with 0 losses into the first list and those with exactly 1 loss into the second, and sort both lists in increasing order.
Complexity: O(n log n) time and O(n) space, where n is the number of matches.
class Solution:
def findWinners(self, matches: List[List[int]]) -> List[List[int]]:
cnt = Counter()
for winner, loser in matches:
if winner not in cnt:
cnt[winner] = 0
cnt[loser] += 1
ans = [[], []]
for x, v in sorted(cnt.items()):
if v < 2:
ans[v].append(x)
return ans