LeetCode 544: Output Contest Matches

Problem Description

Explanation:

To solve this problem, we can use a recursive approach. We start by creating an array of strings representing the initial teams. Then, we recursively pair up teams by concatenating the first and last elements, second and second-to-last elements, and so on. We continue this process until we have only one string left, which represents the final match.

Here are the steps for the algorithm:

  1. Initialize an array of strings representing the teams.
  2. Write a recursive function that takes in the array of strings and recursively pairs up teams until only one string is left.
  3. In each recursive call, create a new array and pair up teams by concatenating the first and last elements, second and second-to-last elements, and so on.
  4. Continue this process until only one string is left, representing the final match.
  5. Return the final match string.

Time Complexity:

The time complexity of this algorithm is O(n log n), where n is the number of teams.

Space Complexity:

The space complexity of this algorithm is O(n), where n is the number of teams.

: :

Solutions

class Solution {
    public String findContestMatch(int n) {
        String[] teams = new String[n];
        for (int i = 1; i <= n; i++) {
            teams[i - 1] = String.valueOf(i);
        }
        return findContestMatchHelper(teams);
    }
    
    private String findContestMatchHelper(String[] teams) {
        if (teams.length == 1) {
            return teams[0];
        }
        
        String[] newTeams = new String[teams.length / 2];
        for (int i = 0; i < teams.length / 2; i++) {
            newTeams[i] = "(" + teams[i] + "," + teams[teams.length - 1 - i] + ")";
        }
        
        return findContestMatchHelper(newTeams);
    }
}

Loading editor...