Output Contest Matches
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.
n = 4"((1,4),(2,3))"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];
}
Explanation
In a fair bracket the strongest seed plays the weakest in every round. So at each step we pair the first element with the last, the second with the second-last, and so on — then repeat on the smaller list until just one combined string remains.
We start with the seeds as strings: a = ["1", "2", ..., "n"]. Each round builds a new list next where element i is the pair "(" + a[i] + "," + a[n-1-i] + ")". In the Python version a[~i] is a shortcut for a[-1-i], the matching element from the end.
Because each round halves the list length, after about log n rounds the list holds a single fully nested string, which we return as a[0].
Example: n = 4 gives ["1","2","3","4"]. Round 1 pairs 1 with 4 and 2 with 3 → ["(1,4)", "(2,3)"]. Round 2 pairs those two → "((1,4),(2,3))", the final bracket.