Output Contest Matches - Problem

During the NBA playoffs, we always set the rather strong team to play with the rather weak team, like making the rank 1 team play with the rank nth team, which is a good strategy to make the contest more interesting.

Given n teams, return their final contest matches in the form of a string. The n teams are labeled from 1 to n, which represents their initial rank (i.e., Rank 1 is the strongest team and Rank n is the weakest team).

We will use parentheses '(', and ')' and commas ',' to represent the contest team pairing. We use the parentheses for pairing and the commas for partition. During the pairing process in each round, you always need to follow the strategy of making the rather strong one pair with the rather weak one.

Input & Output

Example 1 — Basic Case
$ Input: n = 4
Output: ((1,4),(2,3))
💡 Note: Round 1: Team 1 pairs with team 4, team 2 pairs with team 3, creating matches (1,4) and (2,3). Round 2: The two matches compete against each other, forming ((1,4),(2,3))
Example 2 — Minimum Case
$ Input: n = 2
Output: (1,2)
💡 Note: With only 2 teams, the strongest (1) pairs directly with the weakest (2), creating the final match (1,2)
Example 3 — Larger Tournament
$ Input: n = 8
Output: (((1,8),(4,5)),((2,7),(3,6)))
💡 Note: Round 1: (1,8), (2,7), (3,6), (4,5). Round 2: ((1,8),(4,5)), ((2,7),(3,6)). Round 3: Final bracket combines both semifinal matches

Constraints

  • 2 ≤ n ≤ 212
  • n is a power of 2

Visualization

Tap to expand
Output Contest Matches INPUT n = 4 teams (ranked) 1 Strongest 2 3 4 Weakest Pairing Strategy: Strong vs Weak (1, 4) (2, 3) n = 4 Teams: [1, 2, 3, 4] ALGORITHM STEPS 1 Initialize Teams Create list ["1","2","3","4"] 2 Pair Strong + Weak Match i with (n-1-i) 3 Build Recursively Wrap pairs in parentheses 4 Return Result Final nested string Recursive Process: Round 1: [1,2,3,4] --> [(1,4),(2,3)] Round 2: [(1,4),(2,3)] --> ((1,4),(2,3)) OK FINAL RESULT Tournament Bracket FINAL (1,4) (2,3) 1 4 2 3 Output: ((1,4),(2,3)) Matches organized! OK Strong vs Weak pairing Key Insight: The recursive approach pairs teams by matching index i with (n-1-i), ensuring the strongest (rank 1) plays the weakest (rank n). Each round halves the teams, building nested parentheses until one match remains. Time: O(n), Space: O(n) for the recursive string building. TutorialsPoint - Output Contest Matches | Recursive String Building
Asked in
Google 15 Microsoft 12
28.5K Views
Medium Frequency
~15 min Avg. Time
892 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