KatInterview

974. Reorder Data in Log Files

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 requires us to reorder an array of log strings according to a specific set of rules. There are two types of logs: letter-logs and digit-logs. The rules are:

Solution

Reorder Data in Log Files in Python

class Solution:
    def reorderLogFiles(self, logs: List[str]) -> List[str]:
        
        def get_key(log: str):
            # Split log into identifier and content part.
            # The split is done only once at the first space.
            identifier, content = log.split(" ", 1)
            
            # Check if it's a letter-log.
            if content[0].isalpha():
                # For letter-logs, return a tuple for sorting.
                # (0, ...) ensures letter-logs come before digit-logs (which will have (1, ...)).
                # The logs are then sorted by content, and then by identifier for ties.
                return (0, content, identifier)
            else:
                # For digit-logs, return a tuple with a different primary key.
                # This groups them after letter-logs.
                # Python's sort is stable, so digit-logs with the same key (1,) 
                # will maintain their original relative order.
                return (1,)

        # Sort the logs list in-place using the custom key.
        logs.sort(key=get_key)
        return logs

Reorder Data in Log Files in Java

class Solution {
    public String[] reorderLogFiles(String[] logs) {
        // Custom comparator for sorting logs.
        Comparator<String> myComp = new Comparator<String>() {
            @Override
            public int compare(String log1, String log2) {
                // Split each log into two parts: identifier and content.
                String[] split1 = log1.split(" ", 2);
                String[] split2 = log2.split(" ", 2);

                String id1 = split1[0];
                String content1 = split1[1];
                String id2 = split2[0];
                String content2 = split2[1];

                // Check if the first character of content is a digit.
                boolean isDigit1 = Character.isDigit(content1.charAt(0));
                boolean isDigit2 = Character.isDigit(content2.charAt(0));

                // Case 1: Both are letter-logs.
                if (!isDigit1 && !isDigit2) {
                    // Compare content first.
                    int contentCmp = content1.compareTo(content2);
                    if (contentCmp != 0) {
                        return contentCmp;
                    }
                    // If content is the same, compare identifiers.
                    return id1.compareTo(id2);
                }

                // Case 2: One is a letter-log, one is a digit-log.
                if (!isDigit1 && isDigit2) {
                    return -1; // Letter-log comes before digit-log.
                } else if (isDigit1 && !isDigit2) {
                    return 1;  // Digit-log comes after letter-log.
                } else {
                    // Case 3: Both are digit-logs.
                    // Return 0 to maintain their relative order as Arrays.sort is stable.
                    return 0;
                }
            }
        };

        // Sort the logs using the custom comparator.
        Arrays.sort(logs, myComp);
        return logs;
    }
}

Reorder Data in Log Files in C++

class Solution {
public:
    vector<string> reorderLogFiles(vector<string>& logs) {
        // Use stable_sort to maintain the relative order of digit-logs.
        stable_sort(logs.begin(), logs.end(), [](const string& log1, const string& log2) {
            // Find the position of the first space to split identifier and content.
            int space1_pos = log1.find(' ');
            string content1 = log1.substr(space1_pos + 1);

            int space2_pos = log2.find(' ');
            string content2 = log2.substr(space2_pos + 1);

            // Check if logs are letter-logs or digit-logs.
            bool is_letter1 = isalpha(content1[0]);
            bool is_letter2 = isalpha(content2[0]);

            if (is_letter1 && is_letter2) {
                // Both are letter-logs, sort by content then by identifier.
                if (content1 == content2) {
                    string id1 = log1.substr(0, space1_pos);
                    string id2 = log2.substr(0, space2_pos);
                    return id1 < id2;
                }
                return content1 < content2;
            } else if (is_letter1) {
                // log1 is a letter-log, log2 is a digit-log.
                return true; // letter-logs come before digit-logs.
            } else if (is_letter2) {
                // log1 is a digit-log, log2 is a letter-log.
                return false; // digit-logs come after letter-logs.
            } else {
                // Both are digit-logs. For stable_sort, returning false for both
                // (a,b) and (b,a) means they are equivalent, preserving their order.
                return false;
            }
        });
        return logs;
    }
};

Reorder Data in Log Files in TypeScript

function reorderLogFiles(logs: string[]): string[] {
    // Helper to check if a character is a digit.
    const isDigit = (char: string): boolean => char >= '0' && char <= '9';

    // Sort the logs array in-place. Array.prototype.sort() is stable in modern JS engines.
    logs.sort((log1, log2) => {
        // Split each log into identifier and content.
        const spaceIdx1 = log1.indexOf(' ');
        const id1 = log1.substring(0, spaceIdx1);
        const content1 = log1.substring(spaceIdx1 + 1);

        const spaceIdx2 = log2.indexOf(' ');
        const id2 = log2.substring(0, spaceIdx2);
        const content2 = log2.substring(spaceIdx2 + 1);
        
        const isLog1Digit = isDigit(content1[0]);
        const isLog2Digit = isDigit(content2[0]);
        
        // Case 1: both are letter-logs.
        if (!isLog1Digit && !isLog2Digit) {
            // Compare by content first.
            const contentCmp = content1.localeCompare(content2);
            if (contentCmp !== 0) {
                return contentCmp;
            }
            // If content is same, compare by identifier.
            return id1.localeCompare(id2);
        }
        
        // Case 2: one is letter-log, one is digit-log.
        if (!isLog1Digit) { // log1 is letter, log2 is digit
            return -1;
        }
        if (!isLog2Digit) { // log1 is digit, log2 is letter
            return 1;
        }
        
        // Case 3: both are digit-logs.
        // Return 0 to use stable sort's property to maintain relative order.
        return 0;
    });

    return logs;
};

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.