Skip to main content
Back to problems
#555
Medium Algorithms

Split concatenated strings

Array String Greedy
43.6% acceptance
Mar 31, 2026
80
265
You are given an array of strings strs. You could concatenate these strings together into a loop, where for each string, you could choose to reverse it or not. Among all the possible loops Return the lexicographically largest string after cutting the loop, which will make the looped string into a regular one. Specifically, to find the lexicographically largest string, you need to experience two phases: Concatenate all the strings into a loop, where you can reverse some strings or not and connect them in the same order as given. Cut and make one breakpoint in any place of the loop, which will make the looped string into a regular one starting from the character at the cutpoint. And your job is to find the lexicographically largest one among all the possible regular strings.

Solution

Rust
Time O(n³)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn split_looped_string(strs: Vec<String>) -> String {
    let n = strs.len();
    let optimized: Vec<String> = strs.iter().map(|s| {
      let rev: String = s.chars().rev().collect();
      if rev > *s { rev } else { s.clone() }
    }).collect();
    let mut best = String::new();
    for i in 0..n {
      let mut rest = String::new();
      for j in (i + 1)..n {
        rest.push_str(&optimized[j]);
      }
      for j in 0..i {
        rest.push_str(&optimized[j]);
      }
      let rev_i: String = strs[i].chars().rev().collect();
      for s in [strs[i].as_str(), rev_i.as_str()] {
        for k in 0..s.len() {
          let candidate = format!("{}{}{}", &s[k..], &rest, &s[..k]);
          if candidate > best {
            best = candidate;
          }
        }
      }
    }
    best
  }
}