Skip to main content
Back to problems
#544
Medium Algorithms

Output contest matches

String Recursion Simulation
77.5% acceptance
Mar 31, 2026
398
140
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.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn find_contest_match(n: i32) -> String {
    let mut teams: Vec<String> = (1..=n).map(|i| i.to_string()).collect();
    while teams.len() > 1 {
      let mut next = Vec::new();
      let len = teams.len();
      for i in 0..len / 2 {
        next.push(format!("({},{})", teams[i], teams[len - 1 - i]));
      }
      teams = next;
    }
    teams.into_iter().next().unwrap()
  }
}