Skip to main content
Back to problems
#3403
Medium Algorithms

Find the lexicographically largest string from the box i

Two Pointers String Enumeration
41.0% acceptance
Feb 25, 2026
487
127
You are given a string word, and an integer numFriends. Alice is organizing a game for her numFriends friends. There are multiple rounds in the game, where in each round: word is split into numFriends non-empty strings, such that no previous round has had the exact same split. All the split words are put into a box. Find the lexicographically largest string from the box after all the rounds are finished.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn answer_string(word: String, num_friends: i32) -> String {
    let n = word.len();
    let nf = num_friends as usize;
    if nf == 1 {
      return word;
    }
    let base_len = n + 1 - nf;
    let mut best = String::new();
    for i in 0..n {
      let len = base_len.min(n - i);
      let candidate = &word[i..i + len];
      if candidate > best.as_str() {
        best = candidate.to_string();
      }
    }
    best
  }
}