Reorder Data in Log Files

The problem is about reordering logs based on given criteria. We can tackle this problem by first dividing the logs into two types: letter-logs and digit-logs. Then, we sort the letter-logs as per the given requirements, and finally merge the two lists. Here’s how:

  1. Partition Logs:

    • Separate logs into two lists: letter-logs and digit-logs.
  2. Sort Letter-logs:

    • First, sort by contents.
    • If contents are the same, then sort by identifiers.
  3. Merge Logs:

    • Return the sorted letter-logs followed by the original order of digit-logs.

Here’s the Python code to solve this problem:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
    def reorderLogFiles(self, logs: List[str]) -> List[str]:

        # Separate the logs into letter logs and digit logs
        letters, digits = [], []
        for log in logs:
            if log.split()[1].isdigit():
                digits.append(log)
            else:
                letters.append(log)

        # Sort letter logs
        # key for sorting: first by content (log.split()[1:]) then by identifier (log.split()[0])
        letters.sort(key=lambda log: (log.split()[1:], log.split()[0]))

        # Return sorted letter logs followed by digit logs
        return letters + digits

In this solution, we leverage Python’s built-in sorting method and its capability to sort based on multiple criteria to handle the sorting of letter-logs in a concise way.