Output Contest Matches - Problem

Imagine organizing the NBA playoffs where excitement comes from strategic team pairings! ๐Ÿ€

You're given n teams ranked from 1 (strongest) to n (weakest). Your task is to create tournament brackets following this strategy: always pair the strongest remaining team with the weakest remaining team.

Goal: Return the final contest matches as a properly formatted string using:

  • () parentheses for team pairings
  • , commas to separate different matchups

Example: With 4 teams [1,2,3,4], team 1 pairs with team 4, and team 2 pairs with team 3, resulting in "((1,4),(2,3))"

The pairing continues recursively until only one final match remains!

Input & Output

example_1.py โ€” Small Tournament
$ Input: n = 4
โ€บ Output: "((1,4),(2,3))"
๐Ÿ’ก Note: Teams 1,2,3,4 get paired as: strongest(1) with weakest(4), second-strongest(2) with second-weakest(3), resulting in matches (1,4) and (2,3). These two matches form the final bracket.
example_2.py โ€” Larger Tournament
$ Input: n = 8
โ€บ Output: "(((1,8),(4,5)),((2,7),(3,6)))"
๐Ÿ’ก Note: First round: (1,8), (2,7), (3,6), (4,5). Second round: ((1,8),(4,5)) and ((2,7),(3,6)). Final bracket combines these two semi-final matches.
example_3.py โ€” Minimum Case
$ Input: n = 2
โ€บ Output: "(1,2)"
๐Ÿ’ก Note: With only 2 teams, there's just one match: strongest team 1 vs weakest team 2.

Constraints

  • 2 โ‰ค n โ‰ค 212
  • n is a power of 2 (ensures perfect tournament brackets)
  • Teams are numbered from 1 to n where 1 is strongest

Visualization

Tap to expand
๐Ÿ€ Tournament Bracket EvolutionInitial Teams:12345678Round 1 Pairings:(1,8)Strong vs Weak(2,7)(3,6)(4,5)Round 2 Semi-Finals:((1,8),(4,5))((2,7),(3,6))Final Championship:(((1,8),(4,5)),((2,7),(3,6)))
Understanding the Visualization
1
Initial Setup
Start with n teams ranked 1 (strongest) to n (weakest)
2
Strategic Pairing
Pair team 1 with team n, team 2 with team (n-1), etc.
3
Build Brackets
Create match strings and repeat until final bracket
4
Final Result
Return the complete tournament bracket structure
Key Takeaway
๐ŸŽฏ Key Insight: Tournament brackets naturally follow a recursive structure where each round reduces participants by half, making recursion the perfect solution approach!
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
28.5K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen