We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Split Concatenated Strings

Number: 555

Difficulty: Medium

Paid? Yes

Companies: Alibaba


Problem Description

Given an array of strings, you can form a loop by concatenating the strings in the given order. For each string, you have the option to reverse it or leave it as-is. Once the loop is created, you can “cut” the loop at any position so that it becomes a regular (non-circular) string. Your task is to determine the lexicographically largest string that can be obtained among all the possible loops and cut positions.


Key Insights

  • For every string, there are two orientations: the original string and its reversed version.
  • For all strings except the “pivot” (the one in which the cut occurs), choose the lexicographically larger orientation.
  • For the pivot string, test every possible cut position and consider both possible orientations (original and reversed) because the best rotation might come from a split in a non-maximum orientation.
  • The final candidate is built by taking the substring from the cut position to the end of the pivot, appending the concatenation of the best choices of all strings that follow (in loop order), then the best choices of all strings before the pivot, and finally the beginning segment of the pivot.
  • Compare all candidate strings to retrieve the lexicographically largest one.

Space and Time Complexity

Time Complexity: O(n * L * T) where n is the number of strings, L is the average length of the pivot string being processed, and T is the total length of all strings (used when building each candidate). Since T is at most 1000, the overall complexity is acceptable. Space Complexity: O(T), to store the best orientations and build temporary candidate strings.


Solution

The algorithm works as follows:

  1. Precompute an array (bestStrings) where for each string you store the lexicographically larger of the string and its reverse. This will be used for all strings other than the pivot.
  2. For each string (considering it as the pivot), try both orientations (original and reversed). For each orientation, simulate cutting the pivot at every possible index.
  3. Build the candidate string using:
    • The substring of the pivot from the cut point to its end.
    • The concatenation of bestStrings for the strings after the pivot.
    • The concatenation of bestStrings for the strings before the pivot.
    • The prefix of the pivot up to the cut point.
  4. Compare and track the maximum candidate string over all possibilities.
  5. Return the maximum candidate string.

Key data structures and ideas:

  • An array for precomputed best orientations.
  • Iteration over potential pivot indices.
  • String slicing to simulate the circular cut. This approach exhaustively tests all valid rotation points within the constraints, ensuring that the lexicographically largest candidate is returned.

Code Solutions

# Python solution for "Split Concatenated Strings"

def splitConcatenatedStrings(strs):
    # Precompute the best orientation for each string in the list.
    n = len(strs)
    bestStrings = []
    for s in strs:
        # Choose lexicographically larger between the string and its reverse.
        rev = s[::-1]
        bestStrings.append(s if s >= rev else rev)
    
    total_candidate = ""
    total_length = sum(len(s) for s in strs)
    
    # Function to get the full string using pivot candidate and bestStrings for others.
    # The order in the loop is: current pivot split, then all strings after pivot,
    # then all strings before pivot, then the prefix of the pivot.
    def build_candidate(pivot_str, pivot_index, cut_index):
        # Part of pivot starting from the cut point.
        candidate = pivot_str[cut_index:]
        # Append best orientations from pivot_index+1 to end.
        for j in range(pivot_index + 1, n):
            candidate += bestStrings[j]
        # Append best orientations from beginning to pivot_index-1.
        for j in range(0, pivot_index):
            candidate += bestStrings[j]
        # Append the prefix of pivot_str.
        candidate += pivot_str[:cut_index]
        return candidate

    # Iterate over each string considering it as a pivot.
    for i in range(n):
        original = strs[i]
        reversed_str = original[::-1]
        # For the pivot, try both orientations.
        for candidate_version in [original, reversed_str]:
            L = len(candidate_version)
            # Try every possible cut position for the current pivot candidate.
            for cut in range(L):
                candidate = build_candidate(candidate_version, i, cut)
                # Update total_candidate if current candidate is lexicographically greater.
                if candidate > total_candidate:
                    total_candidate = candidate
    return total_candidate

# Example usage:
if __name__ == "__main__":
    test_strs = ["abc", "xyz"]
    print(splitConcatenatedStrings(test_strs))  # Expected Output: "zyxcba"
← Back to All Questions