Skip to main content
Back to problems
#3406
Hard Algorithms

Find the lexicographically largest string from the box ii

Two Pointers String
49.4% acceptance
Mar 31, 2026
7
1
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. A string a is lexicographically smaller than a string b if in the first position where a and b differ, string a has a letter that appears earlier in the alphabet than the corresponding letter in b. If the first min(a.length, b.length) characters do not differ, then the shorter string is the lexicographically smaller one.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn answer_string(word: String, num_friends: i32) -> String {
    if num_friends == 1 {
      return word;
    }
    let n = word.len();
    let max_len = n - (num_friends as usize - 1);
    let bytes = word.as_bytes();
    let mut best_start = 0;
    for i in 1..n {
      if bytes[i] > bytes[best_start] {
        best_start = i;
      } else if bytes[i] == bytes[best_start] {
        let len = max_len.min(n - i).min(n - best_start);
        if word[i..i + len] > word[best_start..best_start + len] {
          best_start = i;
        }
      }
    }
    let end = (best_start + max_len).min(n);
    word[best_start..end].to_string()
  }
}