Reorder Data in Log Files — LeetCode 937 Python Solution

MediumArrayStringSorting
Problem
#937
Pattern
Sorting
Reading time
2 min

The problem

You are given an array of logs. Each log is a space-delimited string of words, where the first word is the identifier.

Example

Input
logs = ["dig1 8 1 5 1","let1 art can","dig2 3 6","let2 own kit dig","let3 art zero"]
Output
["let1 art can","let3 art zero","let2 own kit dig","dig1 8 1 5 1","dig2 3 6"]
Explanation
The letter-log contents are all different, so their ordering is "art can", "art zero", "own kit dig".

Python solution

Python
class Solution:
    def reorderLogFiles(self, logs: List[str]) -> List[str]:
        def f(log: str):
            id_, rest = log.split(" ", 1)
            return (0, rest, id_) if rest[0].isalpha() else (1,)

        return sorted(logs, key=f)

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(n) auxiliary

Pattern: Sorting

Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 937. Reorder Data in Log Files is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.

The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 937. Reorder Data in Log Files?
LeetCode 937. Reorder Data in Log Files is rated Medium on LeetCode.
What is the time complexity of LeetCode 937. Reorder Data in Log Files?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 937. Reorder Data in Log Files?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 937. Reorder Data in Log Files cover?
LeetCode 937. Reorder Data in Log Files is tagged Array, String and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview