Output Contest Matches

medium string recursion simulation

Problem

Given n = 2^k teams seeded 1..n, output the bracket as a nested string where the strongest plays the weakest in each round.

Inputn = 4
Output"((1,4),(2,3))"
At each round, pair first with last, second with second-last, …

def find_contest_matches(n):
    a = [str(i) for i in range(1, n + 1)]
    while len(a) > 1:
        a = [f"({a[i]},{a[~i]})" for i in range(len(a) // 2)]
    return a[0]
function findContestMatch(n) {
  let a = Array.from({ length: n }, (_, i) => String(i + 1));
  while (a.length > 1) {
    const half = a.length / 2;
    const next = [];
    for (let i = 0; i < half; i++) next.push(`(${a[i]},${a[a.length - 1 - i]})`);
    a = next;
  }
  return a[0];
}
class Solution {
    public String findContestMatch(int n) {
        String[] a = new String[n];
        for (int i = 0; i < n; i++) a[i] = String.valueOf(i + 1);
        while (a.length > 1) {
            int half = a.length / 2;
            String[] next = new String[half];
            for (int i = 0; i < half; i++) next[i] = "(" + a[i] + "," + a[a.length - 1 - i] + ")";
            a = next;
        }
        return a[0];
    }
}
string findContestMatch(int n) {
    vector a(n);
    for (int i = 0; i < n; i++) a[i] = to_string(i + 1);
    while (a.size() > 1) {
        int half = a.size() / 2;
        vector next(half);
        for (int i = 0; i < half; i++) next[i] = "(" + a[i] + "," + a[a.size() - 1 - i] + ")";
        a = next;
    }
    return a[0];
}
Time: O(n log n) Space: O(n)