Find the Lexicographically Largest String From the Box II - Problem

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:

  • The string 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.

Input & Output

Example 1 — Basic Case
$ Input: word = "abc", numFriends = 2
Output: "bc"
💡 Note: Possible splits: ["a","bc"], ["ab","c"]. All substrings: "a", "bc", "ab", "c". The lexicographically largest is "bc".
Example 2 — Single Friend
$ Input: word = "hello", numFriends = 1
Output: "hello"
💡 Note: With only 1 friend, the entire word goes to one person, so the answer is "hello".
Example 3 — Multiple Splits
$ Input: word = "zyab", numFriends = 3
Output: "zy"
💡 Note: Possible splits: ["z","y","ab"], ["z","ya","b"], ["zy","a","b"]. All substrings: "z", "y", "ab", "ya", "zy", "a", "b". The lexicographically largest is "zy".

Constraints

  • 1 ≤ word.length ≤ 50
  • 1 ≤ numFriends ≤ word.length
  • word consists of lowercase English letters

Visualization

Tap to expand
Lexicographically Largest String From Box II INPUT word = "abc" a b c 0 1 2 numFriends = 2 Possible Splits: "a" + "bc" "ab" + "c" Box contains: "a", "bc", "ab", "c" All split substrings ALGORITHM STEPS 1 Find Max Start Char Scan for largest char: 'c' 2 Collect Candidates Positions starting with 'c' 3 Compare Suffixes Compare lexicographically 4 Compute Max Length Based on split rules Candidate Analysis Pos Suffix Valid? 1 "bc" OK 2 "c" OK "bc" > "c" lexicographically FINAL RESULT Lexicographically Largest: "bc" Starting at position 1 Length: 2 characters Box Contents Ranked: 1. "bc" [WINNER] 2. "c" 3. "ab" 4. "a" Output: "bc" Key Insight: The lexicographically largest string must start with the maximum character in the word. With numFriends splits, we can always isolate any suffix starting from position 1 onwards, making "bc" the optimal answer as 'b' followed by 'c' is larger than just "c" alone. TutorialsPoint - Find the Lexicographically Largest String From the Box II | Mathematical Optimization
Asked in
Google 25 Microsoft 20 Amazon 15
12.5K Views
Medium Frequency
~35 min Avg. Time
284 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