Find the Lexicographically Largest String From the Box I - 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:

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

Input & Output

Example 1 — Basic Case
$ Input: word = "abc", numFriends = 2
Output: "c"
💡 Note: Possible splits: ["a","bc"], ["ab","c"]. All substrings: "a", "bc", "ab", "c". Lexicographically largest is "c".
Example 2 — Single Friend
$ Input: word = "aba", numFriends = 1
Output: "aba"
💡 Note: Only one split possible: ["aba"]. The answer is the word itself.
Example 3 — Multiple Friends
$ Input: word = "abac", numFriends = 3
Output: "c"
💡 Note: Many possible splits into 3 parts. All possible substrings include "a", "b", "c", "ab", "ba", "ac", etc. The largest is "c".

Constraints

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

Visualization

Tap to expand
Lexicographically Largest String from Box INPUT word = "abc" a idx 0 b idx 1 c idx 2 numFriends = 2 Possible Splits: "a" "bc" "ab" "c" Box contains: ["a","bc","ab","c"] ALGORITHM STEPS 1 Find Max Char Scan word for largest character: 'c' at idx 2 2 Calculate Max Length maxLen = n - numFriends + 1 = 3 - 2 + 1 = 2 3 Search Substrings Starting with 'c', find all valid substrings Candidates starting with 'c': "c" (length 1) [OK] Only one position has 'c' 4 Compare & Select Pick lex largest: "c" FINAL RESULT All strings in box: "a" "bc" "ab" "c" Lexicographic order: "a" < "ab" < "bc" < "c" Output: "c" [OK] Largest found! Key Insight: The lexicographically largest string starts with the largest character in the word. Maximum possible length of any split piece is (n - numFriends + 1). We search all substrings starting with the max char, up to this length, and pick the largest. TutorialsPoint - Find the Lexicographically Largest String From the Box I | Direct Substring Search
Asked in
Google 25 Microsoft 20
23.0K Views
Medium Frequency
~25 min Avg. Time
890 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