Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
When splitting among f friends, a piece can use at most n - f + 1 characters because every other friend needs at least one. For a fixed starting position, its longest feasible piece is lexicographically at least as large as any shorter prefix of that piece. Thus only the longest candidate from each start matters.
Approach
If there is only one friend, return the entire word. Otherwise set the length cap to n - numFriends + 1. Python first compares all substrings of exactly that length, then builds and compares the shorter suffixes near the end. JavaScript handles both cases in one scan by slicing from each start through at most that many characters.
Both versions cover the longest feasible piece at every starting position. A capped-length piece leaves exactly enough characters for the other pieces; a shorter suffix leaves a prefix that can be split among the remaining friends. Return the greatest candidate found using ordinary lexicographic string comparison.
class Solution:
def answerString(self, word: str, numFriends: int) -> str:
if numFriends == 1: return word
n = len(word)
target = n - numFriends + 1
selected = ''
for i in range(target - 1, n):
curr = word[i - (target - 1) : i + 1]
if not selected or curr > selected: selected = curr
curr = ''
for i in range(n - 1, n - target, -1):
curr = word[i] + curr
if not selected or curr > selected: selected = curr
return selectedComplexity analysis
Let n = word.length. Both solutions construct and compare O(n) candidate slices of length up to n, giving O(n^2) worst-case time and O(n) auxiliary space for temporary and returned strings. Every candidate is capped at the longest piece permitted by the split.
