Find Players With Zero or One Losses - Hashmap [JS]

Description

Solution: Hashmap

Use a hashmap to count the number of losses for each player.
In case a player hasn't lost any matches, we need to give it a count of 0 so that they are included in the hashmap.

Get the players with count 0 and the players with count 1.
Note: In JavaScript, the object keeps keys in ascending order, so we don't need to sort before returning.

Time Complexity: O(n)
Space Complexity: O(n)

var findWinners = function(matches) {
  let lost = {};
  for (let [winner, loser] of matches) {
    lost[winner] = (lost[winner] || 0);
    lost[loser] = (lost[loser] || 0) + 1;
  }
  let res = [[], []];
  for (let player in lost) {
    if (lost[player] === 0) res[0].push(+player);
    else if (lost[player] === 1) res[1].push(+player);
  }
  return res;
};

javascript

Comments

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]