Find the Lexicographically Largest String From the Box II Problem
Description
LeetCode Problem 3406.
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.
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.
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 <= 2 * 10^5wordconsists only of lowercase English letters.1 <= numFriends <= word.length
Solution
Approach: Largest Suffix with Two Pointers
As in the easier version, the answer is the largest substring that starts somewhere and is at most n - numFriends + 1 characters long. The largest such piece is a prefix of the lexicographically largest suffix of word, so it is enough to find that suffix once and cut it to the allowed length. With numFriends = 1 return the whole word.
To find the largest suffix in linear time, keep two candidate starts i < j and a match length k:
- If
word[i + k] == word[j + k], increasek. - If
word[i + k] < word[j + k], the starti(and every start up toi + k) loses: seti = i + k + 1, make surej > i, and resetk. - Otherwise the start
j(and every start up toj + k) loses: setj = j + k + 1and resetk.
When j + k reaches the end, the suffix starting at i is the largest.
Complexity: O(n) time, O(1) extra space besides the output.
class Solution:
def answerString(self, word: str, numFriends: int) -> str:
if numFriends == 1:
return word
s = self.lastSubstring(word)
return s[: len(word) - numFriends + 1]
def lastSubstring(self, s: str) -> str:
i, j, k = 0, 1, 0
while j + k < len(s):
if s[i + k] == s[j + k]:
k += 1
elif s[i + k] < s[j + k]:
i += k + 1
k = 0
if i >= j:
j = i + 1
else:
j += k + 1
k = 0
return s[i:]