3403. Find the Lexicographically Largest String From the Box I
Description
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 intonumFriends
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.
Example 1:
Input: word = "dbca", numFriends = 2
Output: "dbc"
Explanation:
All possible splits are:
"d"
and"bca"
."db"
and"ca"
."dbc"
and"a"
.
Example 2:
Input: word = "gggg", numFriends = 4
Output: "g"
Explanation:
The only possible split is: "g"
, "g"
, "g"
, and "g"
.
Constraints:
1 <= word.length <= 5 * 103
word
consists only of lowercase English letters.1 <= numFriends <= word.length
Solutions
Solution 1: Enumerate Substring Left Endpoints
If we fix the left endpoint of the substring, the longer the substring, the larger its lexicographical order. Suppose the left endpoint of the substring is \(i\), and the minimum length of the remaining substrings is \(\text{numFriends} - 1\), then the right endpoint of the substring can be up to \(\min(n, i + n - (\text{numFriends} - 1))\), where \(n\) is the length of the string. Note that we are talking about left-closed, right-open intervals.
We enumerate all possible left endpoints, extract the corresponding substrings, compare their lexicographical order, and finally obtain the lexicographically largest substring.
The time complexity is \(O(n^2)\), and the space complexity is \(O(n)\), where \(n\) is the length of the string.
1 2 3 4 5 6 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
1 2 3 4 5 6 7 8 9 10 11 |
|
1 2 3 4 5 6 7 8 9 10 11 12 |
|