We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Output Contest Matches

Number: 544

Difficulty: Medium

Paid? Yes

Companies: Google


Problem Description

Given n teams (where n is a power of two) labeled from 1 to n (with 1 being the strongest), you need to simulate the contest matches where in every round the strongest available team is paired with the weakest available team. The pairing is represented with parentheses and commas. For instance, when n = 4, the sequence of rounds produces the final result "((1,4),(2,3))".


Key Insights

  • The problem is essentially simulating rounds of matches until a single final match remains.
  • In each round, pair the first element (strongest) with the last element (weakest).
  • The list of pairing results is updated at the end of each round until only one pairing (the final match) remains.
  • A recursion or iterative simulation can be used to perform these rounds.

Space and Time Complexity

Time Complexity: O(n) for setup and O(n) per round, but since n halves each round, the overall complexity is O(n). Space Complexity: O(n) to store the current round's pairing strings.


Solution

We solve the problem by simulating the contest rounds. Start by converting each team number into a string. Then, repeatedly form new pairings by taking the team from the front and pairing it with the team from the end of the list. Replace the current list with this new list of pairings. Continue until just one pairing remains, which is the final contest match representation.

Key data structures and steps:

  • Use a list (or its equivalent in other languages) to hold team labels or pairing strings.
  • Loop until one pairing remains by pairing the first and last elements.
  • No special data structures are needed beyond a simple list and string concatenation.

Code Solutions

# Python implementation
def findContestMatch(n):
    # Initialize teams as a list of strings from "1" to str(n)
    teams = [str(i) for i in range(1, n + 1)]
    
    # Loop until only one final pairing remains
    while len(teams) > 1:
        new_round = []
        # Pair teams: first with last, second with second last, etc.
        for i in range(len(teams) // 2):
            pairing = "(" + teams[i] + "," + teams[-1 - i] + ")"
            new_round.append(pairing)
        teams = new_round  # Update teams with the results of the current round
    
    # Return the final pairing as the result
    return teams[0]

# Example usage:
print(findContestMatch(8))
← Back to All Questions