Skip to content

Commit c085479

Browse files
committed
feat: Solves Tournament Winner
- AlgoExpert
1 parent 0120132 commit c085479

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

arrays-strings/tournament-winner.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* AlgoExpert
3+
*
4+
* Given an array of pairs representing the teams that have competed against each
5+
* other and an array containing the results of each competition, write a
6+
* function that returns the winner of the tournament. The input arrays are named
7+
* competitions and results, respectively. The competitions array has elements in
8+
* the form of [homeTeam, awayTeam], where each team is a string of at most 30
9+
* characters representing the name of the team. The results array contains information
10+
* about the winner of each corresponding competition in the competitions array. Specifically,
11+
* results[i] denotes the winner of competitions[i], where a 1 in the results array means
12+
* that the home team in the corresponding competition won and a 0 means that the
13+
* away team won.
14+
*/
15+
16+
/**
17+
* @param {string[][]} competitions
18+
* @param {string[]} results
19+
* @returns {string}
20+
*/
21+
function tournamentWinner(competitions, results) {
22+
const pointsTable = new Map();
23+
const winnerTable = {
24+
teamName: '',
25+
totalPoints: -Infinity
26+
};
27+
28+
// O(n) Extract the total points for every team
29+
competitions.forEach((competition, idx) => {
30+
const winnerTeam = competition[1 - results[idx]];
31+
32+
let newPoints = pointsTable.get(winnerTeam) || 0;
33+
newPoints += 3;
34+
pointsTable.set(winnerTeam, newPoints);
35+
36+
if (newPoints > winnerTable.totalPoints) {
37+
winnerTable.teamName = winnerTeam;
38+
winnerTable.totalPoints = newPoints;
39+
}
40+
});
41+
42+
return winnerTable.teamName;
43+
}

0 commit comments

Comments
 (0)