KatInterview

555. Split Concatenated Strings

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find the lexicographically largest string that can be formed from a given array of strings strs. We can arrange these strings in a loop in their given order. For each string, we have the choice to either use it as is or reverse it. After forming this loop, we can cut it at any point to create a linear string. We need to find the best combination of reversals and the best cut point to produce the lexicographically largest possible linear string.

Solution

Split Concatenated Strings in Python

class Solution:
    def splitLoopedString(self, strs: List[str]) -> str:
        # Step 1: Pre-process to maximize the non-split parts of the loop.
        # For each string, choose the lexicographically larger version between itself and its reverse.
        # This is a greedy choice to maximize the "background" string.
        max_strs = []
        for s in strs:
            rev_s = s[::-1]
            if s > rev_s:
                max_strs.append(s)
            else:
                max_strs.append(rev_s)

        ans = ""
        n = len(strs)

        # Step 2: Iterate through each string, considering it as the one to be split.
        for i in range(n):
            # The string at index `i` can be in its original or reversed form.
            # `max_strs[i]` is one form, its reverse is the other.
            s1 = max_strs[i]
            s2 = s1[::-1]

            # Concatenate the rest of the loop.
            # This part is formed by the maximized strings from `max_strs`.
            rest_of_loop_parts = max_strs[i+1:] + max_strs[:i]
            rest_of_loop = "".join(rest_of_loop_parts)
            
            # Try splitting s1 at every possible point k
            for k in range(len(s1)):
                candidate = s1[k:] + rest_of_loop + s1[:k]
                if candidate > ans:
                    ans = candidate
            
            # Try splitting s2 at every possible point k
            for k in range(len(s2)):
                candidate = s2[k:] + rest_of_loop + s2[:k]
                if candidate > ans:
                    ans = candidate
                    
        return ans

Split Concatenated Strings in Java

class Solution {
    public String splitLoopedString(String[] strs) {
        int n = strs.length;

        // Step 1: Pre-process to maximize the non-split parts of the loop.
        // For each string, choose the lexicographically larger version between itself and its reverse.
        for (int i = 0; i < n; i++) {
            String reversed = new StringBuilder(strs[i]).reverse().toString();
            if (strs[i].compareTo(reversed) < 0) {
                strs[i] = reversed;
            }
        }

        String maxStr = "";

        // Step 2: Iterate through each string, considering it as the one to be split.
        for (int i = 0; i < n; i++) {
            // The `strs` array now contains the lexicographically maximized versions.
            // But for the string being split, we must consider both its original and reversed form.
            // Here, strs[i] is already one of them (the bigger one). We find its reverse.
            String s1 = strs[i];
            String s2 = new StringBuilder(s1).reverse().toString();

            // Concatenate the rest of the loop using a StringBuilder for efficiency.
            StringBuilder restOfLoopBuilder = new StringBuilder();
            for (int j = i + 1; j < n; j++) {
                restOfLoopBuilder.append(strs[j]);
            }
            for (int j = 0; j < i; j++) {
                restOfLoopBuilder.append(strs[j]);
            }
            String restOfLoop = restOfLoopBuilder.toString();

            // Helper function to check all splits for a given string and the rest of the loop
            maxStr = checkSplits(s1, restOfLoop, maxStr);
            maxStr = checkSplits(s2, restOfLoop, maxStr);
        }

        return maxStr;
    }

    private String checkSplits(String s, String rest, String maxStr) {
        for (int k = 0; k < s.length(); k++) {
            // Building candidate string without creating too many intermediate strings
            StringBuilder candidateBuilder = new StringBuilder();
            candidateBuilder.append(s.substring(k));
            candidateBuilder.append(rest);
            candidateBuilder.append(s.substring(0, k));
            String candidate = candidateBuilder.toString();
            
            if (candidate.compareTo(maxStr) > 0) {
                maxStr = candidate;
            }
        }
        return maxStr;
    }
}

Split Concatenated Strings in C++

class Solution {
public:
    string splitLoopedString(vector<string>& strs) {
        int n = strs.size();
        // Step 1: Pre-process to maximize the non-split parts of the loop.
        // For each string, choose the lexicographically larger version between itself and its reverse.
        for (int i = 0; i < n; ++i) {
            string reversed_s = strs[i];
            reverse(reversed_s.begin(), reversed_s.end());
            if (reversed_s > strs[i]) {
                strs[i] = reversed_s;
            }
        }

        string max_str = "";

        // Step 2: Iterate through each string, considering it as the one to be split.
        for (int i = 0; i < n; ++i) {
            // The `strs` vector now contains the lexicographically maximized versions.
            // But for the string being split, we must consider both its original and reversed form.
            string s1 = strs[i];
            string s2 = s1;
            reverse(s2.begin(), s2.end());

            // Concatenate the rest of the loop.
            string rest_of_loop = "";
            for (int j = i + 1; j < n; ++j) {
                rest_of_loop += strs[j];
            }
            for (int j = 0; j < i; ++j) {
                rest_of_loop += strs[j];
            }

            // Check candidates from s1 (the version from max_strs)
            for (int k = 0; k < s1.length(); ++k) {
                string candidate = s1.substr(k) + rest_of_loop + s1.substr(0, k);
                if (candidate > max_str) {
                    max_str = candidate;
                }
            }
            
            // Check candidates from s2 (the reversed version of s1)
            for (int k = 0; k < s2.length(); ++k) {
                string candidate = s2.substr(k) + rest_of_loop + s2.substr(0, k);
                if (candidate > max_str) {
                    max_str = candidate;
                }
            }
        }

        return max_str;
    }
};

Split Concatenated Strings in TypeScript

function splitLoopedString(strs: string[]): string {
    const n = strs.length;

    // Step 1: Pre-process to maximize the non-split parts of the loop.
    // For each string, choose the lexicographically larger version.
    const maxStrs: string[] = strs.map(s => {
        const reversedS = s.split('').reverse().join('');
        return s > reversedS ? s : reversedS;
    });

    let maxStr = "";

    // Step 2: Iterate through each string, considering it as the one to be split.
    for (let i = 0; i < n; i++) {
        // The string at index `i` can be in its original or reversed form.
        // `maxStrs[i]` is one form, its reverse is the other.
        const s1 = maxStrs[i];
        const s2 = s1.split('').reverse().join('');

        // Concatenate the rest of the loop.
        let restOfLoop = "";
        for (let j = i + 1; j < n; j++) {
            restOfLoop += maxStrs[j];
        }
        for (let j = 0; j < i; j++) {
            restOfLoop += maxStrs[j];
        }

        // Check candidates from s1
        for (let k = 0; k < s1.length; k++) {
            const candidate = s1.substring(k) + restOfLoop + s1.substring(0, k);
            if (candidate > maxStr) {
                maxStr = candidate;
            }
        }

        // Check candidates from s2
        for (let k = 0; k < s2.length; k++) {
            const candidate = s2.substring(k) + restOfLoop + s2.substring(0, k);
            if (candidate > maxStr) {
                maxStr = candidate;
            }
        }
    }

    return maxStr;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.