Find Players With Zero or One Losses

Updated on 28 May, 2025
Find Players With Zero or One Losses header image

Problem Statement

In the given task, you are provided with an array matches, where each element is a pair [winneri, loseri]. Each pair represents a match where the player winneri defeated the player loseri. Your goal is to analyze the match outcomes and categorize the players based on their match results:

  1. The first subset includes players who have not lost any match.
  2. The second subset contains those who have lost exactly one match.

The output should be a list having two lists: the first for players with no defeats and the second for players with exactly one loss, both sorted in ascending order. The focus is on players involved in at least one match, ensuring uniqueness in match outcomes.

Examples

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 <= 105
  • matches[i].length == 2
  • 1 <= winneri, loseri <= 105
  • winneri != loseri
  • All matches[i] are unique.

Approach and Intuition

To solve the problem, the solution needs to keep track of how many matches each player has lost, and also note whether each player has won any matches.

Steps to Solve the Problem

  1. Use two separate data structures, preferably dictionaries or hash maps:

    • One to store losses (loss_count) where the key is the player and the value is the number of times they've lost.
    • Another to keep track of players who have participated (played_players), ensuring they've been involved in at least one match.
  2. Traverse through each match in matches to update these data structures:

    • Add both winner and loser to the played_players set.
    • For the loser in each match, increment their loss count in the loss_count.
  3. After processing all matches:

    • Initialize two lists: no_losses for players with zero losses and one_loss for players with exactly one loss.
    • Check each player in played_players:
      • If their loss count is zero (or they are not in loss_count), add them to no_losses.
      • If their loss count is one, add them to one_loss.
  4. Finally, sort both lists no_losses and one_loss in ascending order and return them as part of the final answer list.

By this strategy, we not only efficiently categorize players based on their match outcomes but also adhere to the constraint of counting only those players who have engaged in at least one match. The use of hash maps ensures that time complexity remains reasonable even when dealing with large inputs.

Solutions

  • C++
  • Java
  • Python
cpp
class Solution {
public:
    vector<vector<int>> getWinners(vector<vector<int>>& games) {
        vector<int> lossCounts(100001, -1);

        for (auto& game : games) {
            int champ = game[0], defeated = game[1];
            if (lossCounts[champ] == -1) {
                lossCounts[champ] = 0;
            }
            if (lossCounts[defeated] == -1) {
                lossCounts[defeated] = 1;
            } else {
                lossCounts[defeated]++;
            }
        }

        vector<vector<int>> result(2, vector<int>());
        for (int i = 1; i < 100001; ++i) {
            if (lossCounts[i] == 0) {
                result[0].push_back(i);
            } else if (lossCounts[i] == 1) {
                result[1].push_back(i);
            }
        }

        return result;
    }
};

The provided C++ solution is designed to identify players with zero or one losses based on a series of games. Each game results are represented in a two-dimensional vector where each sub-vector contains two integers. The first integer is the ID of the winning player, and the second is the ID of the losing player.

  • Initialize lossCounts as a vector with 100001 elements set to -1. This accounts for player IDs up to 100000, initializing their loss counts to an undefined state (-1).

  • Iterate through each game result:

    • For the winner (identified by the first element in the sub-vector), if their loss count is -1 (undefined), set it to 0.
    • For the loser (second element in the sub-vector), increase their loss count by one. If their loss count was previously undefined, initialize it to 1.
  • Create a result vector containing two sub-vectors:

    • First sub-vector stores IDs of players who have zero losses.
    • Second sub-vector stores IDs of players with exactly one loss.
  • Fill each sub-vector by iterating through lossCounts:

    • If a player's loss count is 0, add their ID to the first sub-vector.
    • If a player's loss count is 1, add their ID to the second sub-vector.

This efficient method ensures that at the end of the iteration through games, the result vector provides a clear distinction between players with zero losses and those with only one loss.

java
class Solution {
    public List<List<Integer>> getWinners(int[][] matchData) {
        int[] countLosses = new int[100001];
        Arrays.fill(countLosses, -1);

        for (int[] match : matchData) {
            int victor = match[0], defeated = match[1];
            if (countLosses[victor] == -1) {
                countLosses[victor] = 0;
            }
            if (countLosses[defeated] == -1) {
                countLosses[defeated] = 1;
            } else {
                countLosses[defeated]++;
            }
        }

        List<List<Integer>> result =
            Arrays.asList(new ArrayList<>(), new ArrayList<>());
        for (int i = 1; i < 100001; ++i) {
            if (countLosses[i] == 0) {
                result.get(0).add(i);
            } else if (countLosses[i] == 1) {
                result.get(1).add(i);
            }
        }

        return result;
    }
}

The given Java solution addresses the problem of identifying players who have either zero or one loss using an array to track the number of losses. The approach uses the following methodology:

  1. Initialize an array countLosses to keep record of each player's losses. Initially, set all values to -1, which indicates that the player has not been involved in any matches yet.
  2. Iterate over the provided match data where each entry includes two players: the victor and the defeated. Update countLosses such that if it's the first time the victor appears, their count is set to zero, representing no losses. For the defeated, if it's their first appearance, their count is set directly to one, otherwise increment their current loss count.
  3. Prepare the final result as a list of two lists: one for players with zero losses and another for players with one loss. Iterate over countLosses and populate these lists based on the loss count for each player.

This solution allows efficient tracking and categorization of players based on their loss records from match data, facilitating easy retrieval of players who have been either undefeated or defeated only once. The use of an integer array for direct access to player data is a space-efficient and time-efficient choice, making the solution suitable for large datasets within the constraints given (player identifiers up to 100000).

python
def get_winners_and_losers(self, games: List[List[int]]) -> List[List[int]]:
        defeat_count = [-1] * 100001

        for victor, defeated in games:
            if defeat_count[victor] == -1:
                defeat_count[victor] = 0
            if defeat_count[defeated] == -1:
                defeat_count[defeated] = 1
            else:
                defeat_count[defeated] += 1

        result = [[], []]
        for player in range(100001):
            if defeat_count[player] == 0:
                result[0].append(player)
            elif defeat_count[player] == 1:
                result[1].append(player)

        return result

The Python function get_winners_and_losers efficiently identifies and categorizes players based on their number of losses from a list of game results. Here's how it works:

  1. A list called defeat_count is initialized, setting the loss count of each player to -1 to indicate they haven't been defeated yet.

  2. Through iteration of the games list, players' defeat counts are updated:

    • If it's the first time the victor is encountered, their loss count remains at 0.
    • The defeated player's count is set to 1 if it's their first loss or incremented if they've already been defeated.
  3. The function then initializes a result list with two sub-lists to hold players with zero and one loss respectively.

  4. Iterates over all possible players:

    • If a player has zero defeats, they are appended to the first sub-list.
    • If a player has one defeat, they are appended to the second sub-list.
  5. Finally, the result list is returned, offering a clear separation between players who are undefeated or have just one loss. This method ensures a comprehensive list of players in an optimal manner based on their performance in the given dataset of games.

Comments

No comments yet.