0

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;
  }
}
  • 1
    My best advice would be to step through this with your debugger, and find out exactly where its behaviour deviates from what you expect. – Dawood ibn Kareem May 25 '22 at 01:59
  • Thank you! @DawoodibnKareem This was in a AlgoExpert code editor problem so that wasn't an option, but you're right, next time I face this issue I will insert into my IDE. – Jessica Boyle May 26 '22 at 11:51

1 Answers1

0

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)) {
blacktide
  • 10,654
  • 8
  • 33
  • 53