Split Concatenated Strings - Problem

You are given an array of strings strs. You could concatenate these strings together into a loop, where for each string, you could choose to reverse it or not. Among all the possible loops, return the lexicographically largest string after cutting the loop.

Specifically, to find the lexicographically largest string, you need to experience two phases:

  1. Concatenate all the strings into a loop, where you can reverse some strings or not and connect them in the same order as given.
  2. Cut and make one breakpoint in any place of the loop, which will make the looped string into a regular one starting from the character at the cutpoint.

Your job is to find the lexicographically largest one among all the possible regular strings.

Input & Output

Example 1 — Basic Case
$ Input: strs = ["abc", "xyz"]
Output: "zyxcba"
💡 Note: We can reverse both strings to get "cba" and "zyx", forming loop "cbazyx". Cutting at position 3 gives "zyxcba" which is lexicographically largest.
Example 2 — Single String
$ Input: strs = ["abc"]
Output: "cba"
💡 Note: With one string, we can either use "abc" or reverse it to "cba". "cba" is lexicographically larger.
Example 3 — Multiple Options
$ Input: strs = ["a", "aa", "aaa"]
Output: "aaaaaaa"
💡 Note: All strings contain only 'a', so any arrangement gives the same result: 7 consecutive 'a's.

Constraints

  • 1 ≤ strs.length ≤ 1000
  • 1 ≤ strs[i].length ≤ 1000
  • 1 ≤ sum of strs[i].length ≤ 1000
  • strs[i] consists of lowercase English letters only

Visualization

Tap to expand
INPUTALGORITHMRESULTabcxyzString array to arrangein optimal circular loop1Find max character2Filter flip combinations3Create circular loop4Find optimal cut positionzMax charzyxcbaLexicographicallylargest resultAchieved by reversingboth strings andcutting at position 3Key Insight:Only strings containing the maximum character need to be considered for flipping,dramatically reducing the search space while maintaining optimality.TutorialsPoint - Split Concatenated Strings | Greedy Optimization
Asked in
Google 15 Amazon 8 Facebook 12 Microsoft 6
18.5K Views
Medium Frequency
~35 min Avg. Time
287 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