javaalgorithmhashtabletournament

AlgoExpert Question, Tournament Winner, Not passing all test cases


Tournament Winner: There's an algorithms tournament taking place in which teams of programmers compete against each other to solve algorithmic problems as fast as possible. Teams compete in a round robin, where each team faces off against all other teams. Only two teams compete against each other at a time. (Rest of problem in screenshot attached).

enter image description here

My code is only passing 6/10 test cases. I know my "bestTeam" is not getting updated but I'm not sure why. Please help me figure out where I am going wrong.

Test Case Failed:

Input:

{
  "competitions": [
    ["HTML", "C#"],
    ["C#", "Python"],
    ["Python", "HTML"]
  ],
  "results": [0, 0, 1]
}

My result was "C#" when it should be "Python"

class Program {

  public String tournamentWinner(
      ArrayList<ArrayList<String>> competitions, ArrayList<Integer> results) {
    
        Hashtable<String, Integer> tableTeamNameAndPoints = new Hashtable<>();
        String bestTeam = "";

        tableTeamNameAndPoints.put(bestTeam, 0);

        for(int i = 0; i < competitions.size(); i++){
          String winningTeamName = results.get(i) == 0 ? 
            competitions.get(i).get(1) : competitions.get(i).get(0);

          if(!tableTeamNameAndPoints.contains(winningTeamName)){
            tableTeamNameAndPoints.put(winningTeamName, 3);          
        }
          if(tableTeamNameAndPoints.contains(winningTeamName)){
            Integer updatedScore = tableTeamNameAndPoints.get(winningTeamName) + 3;
            tableTeamNameAndPoints.put(winningTeamName, updatedScore);          
          }

        if (tableTeamNameAndPoints.get(winningTeamName) > tableTeamNameAndPoints.get(bestTeam)){
            bestTeam = winningTeamName;
          }
      }
        
        return bestTeam;
  }
}

Solution

  • You should use containsKey on your Hashtable instead of contains on this line:

    if (!tableTeamNameAndPoints.contains(winningTeamName)) {
    

    When you use contains, you're checking if the Hashtable contains a key that maps to the value provided. It's equivalent to the containsValue method.

    You can also remove the second if statement which is not needed (the condition is always true) and has the same contains problem:

    if (tableTeamNameAndPoints.contains(winningTeamName)) {