Find the Lexicographically Largest String From the Box I Problem
Description
LeetCode Problem 3403.
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:
wordis split intonumFriendsnon-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 * 10^3wordconsists only of lowercase English letters.1 <= numFriends <= word.length
Solution
Approach: Try Every Start
When the start of a piece is fixed, a longer piece is never smaller, so each piece should be as long as possible. If the piece starts at i, the other numFriends - 1 pieces need at least one character each, so the piece can end at most at min(n, i + n - (numFriends - 1)) (exclusive).
Try every start i, cut that longest piece and keep the largest one. With numFriends = 1 the whole word is returned.
Complexity: O(n^2) time, O(n) extra space.
class Solution:
def answerString(self, word: str, numFriends: int) -> str:
if numFriends == 1:
return word
n = len(word)
return max(word[i : i + n - (numFriends - 1)] for i in range(n))