LeetCode 937: Reorder Data in Log Files Solution

Master LeetCode problem 937 (Reorder Data in Log Files), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

937. Reorder Data in Log Files

Problem Explanation

Explanation

To solve this problem, we need to separate the letter-logs from the digit-logs, sort the letter-logs according to the given rules, and then append the digit-logs at the end in their original order.

  1. Separate the logs into two lists: letter-logs and digit-logs.
  2. Sort the letter-logs based on content and identifier.
  3. Concatenate the sorted letter-logs with the digit-logs.

Time Complexity: The time complexity of this solution is O(N*logN) where N is the number of logs.

Space Complexity: The space complexity is O(N).

Solution Code

import java.util.Arrays;
import java.util.Comparator;

class Solution {
    public String[] reorderLogFiles(String[] logs) {
        Arrays.sort(logs, new Comparator<String>() {
            @Override
            public int compare(String log1, String log2) {
                String[] split1 = log1.split(" ", 2);
                String[] split2 = log2.split(" ", 2);
                boolean isDigit1 = Character.isDigit(split1[1].charAt(0));
                boolean isDigit2 = Character.isDigit(split2[1].charAt(0));

                if (!isDigit1 && !isDigit2) {
                    int cmp = split1[1].compareTo(split2[1]);
                    if (cmp != 0) {
                        return cmp;
                    }
                    return split1[0].compareTo(split2[0]);
                } else if (isDigit1 && isDigit2) {
                    return 0;
                } else if (isDigit1) {
                    return 1;
                } else {
                    return -1;
                }
            }
        });
        return logs;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 937 (Reorder Data in Log Files)?

This page provides optimized solutions for LeetCode problem 937 (Reorder Data in Log Files) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 937 (Reorder Data in Log Files)?

The time complexity for LeetCode 937 (Reorder Data in Log Files) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 937 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 937 in Java, C++, or Python.

Back to LeetCode Solutions