A regatta committee is drawing up a single-elimination knockout series for a fleet of n sailboats, seeded by strength from 1 (strongest) to n (weakest); n is guaranteed to be a power of two. In the first round the committee lines the boats up in seed order and pairs the boat at the front of the line with the boat at the back, then the new front with the new back, and so on working inward, so seed 1 races seed n, seed 2 races seed n-1, and so forth. Each of those pairings is then treated as a single unit and lined up in the same left-to-right order in which the pairs were formed; the committee applies the exact same front-with-back rule to this new, shorter line, and keeps repeating the process -- always pairing the current front unit with the current back unit and working inward -- until only one unit remains, which describes the entire bracket.
Formally, let the current round be a list of groups g_1, g_2, ..., g_k written left to right (initially the k = n boats themselves, in seed order). The next round's list is formed by combining g_i and g_{k+1-i} into a single group "(g_i,g_{k+1-i})" for i = 1, 2, ..., k/2, keeping the results in that same left-to-right order. Repeat this halving process until exactly one group remains, and print it.
A single line containing one integer n.
A single line containing the fully nested bracket string built by the process above, using only digits, commas, and parentheses -- no spaces anywhere. If n = 1 there is nothing to pair, so the output is simply "1".
Example 1
Input
4
Expected
((1,4),(2,3))
Explanation
Boats 1..4 line up. Round 1 pairs front-with-back: (1,4) and (2,3), giving the two-unit line ["(1,4)", "(2,3)"]. Round 2 pairs the only front-with-back pair left, combining them into "((1,4),(2,3))", which is the final single unit.
Example 2
Input
8
Expected
(((1,8),(4,5)),((2,7),(3,6)))
Explanation
Boats 1..8 line up. Round 1 pairs (1,8), (2,7), (3,6), (4,5), giving four units. Round 2 pairs the new front-with-back: "(1,8)" with "(4,5)" to get "((1,8),(4,5))", and "(2,7)" with "(3,6)" to get "((2,7),(3,6))". Round 3 combines these last two units into "(((1,8),(4,5)),((2,7),(3,6)))".
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →