Problem 937

Abstract / Summary

Reorder log files so letter-identified logs come first in order and digit-identified logs follow in original order.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0937.py

class Solution:
    def reorderLogFiles(self, logs: List[str]) -> List[str]:
        # extract letters
        letters = []
        for l in logs:
            if l[-1] > "9":
                id, content = l.split(" ", 1)
                letters.append(( content, id ))

        # sort them
        for content, id in sorted(letters):
            yield id + " " + content

        # unsorted digits
        for l in logs:
            if l[-1] <= "9":
                yield l
17 lines | 491 bytes | submitted May 28, 2024 | GitHub   25% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 57% (700k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Sorting
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided Solution class implements a method reorderLogFiles that receives a list of log strings and returns them in a specific order. The logs are divided into two categories: those whose content consists of letters and those whose content consists of digits. Letter logs are sorted lexicographically by their content and identifier, while digit logs retain their original relative order. The method uses a generator pattern to produce the reordered logs on demand.

Key Steps

1. Separate Letter Logs

The first loop iterates over every log entry. By examining the last character of the string (l[-1] > "9"), the code determines whether the log ends with a letter, which implies that the entire content is alphabetic. For such logs, the identifier and the content are split at the first space, and a tuple containing the content and identifier is stored.

letters = []
for l in logs:
    if l[-1] > "9":
        id, content = l.split(" ", 1)
        letters.append((content, id))

2. Sort Letter Logs

The collected tuples are sorted using Python’s built-in sorted. Because each tuple is ordered as (content, id), the sort first compares the content strings and, when those are equal, falls back to the identifier. The sorted tuples are then yielded in the format id + " " + content.

for content, id in sorted(letters):
    yield id + " " + content

3. Emit Digit Logs in Original Order

A second pass over the original logs list checks for entries whose last character is a digit (l[-1] <= "9"). Those logs are yielded directly, preserving the order in which they appeared in the input.

for l in logs:
    if l[-1] <= "9":
        yield l

Edge Cases Handled

The implementation implicitly handles several edge conditions:

  • Mixed Content Lengths: By checking only the final character, the code correctly classifies logs regardless of how many words appear in the content. Whether the content contains a single word or many, the classification relies on the nature of the last character, which is sufficient because digit logs are guaranteed to end with a digit.

  • Identical Content with Different Identifiers: When two letter logs share the same content, the tuple ordering (content, id) ensures that the identifiers are used as a secondary key, resulting in a deterministic order that respects the problem’s requirement.

  • Empty or Single-Character Logs: If a log consists of only an identifier and a single character content, the split operation still succeeds, and the classification based on the last character remains valid.

  • Preservation of Digit Log Order: By iterating over the original list a second time and yielding digit logs as they appear, the relative ordering of digit logs is maintained even if they are interleaved with letter logs in the input.

Performance Optimizations

The code exhibits several deliberate choices that improve runtime efficiency:

  • Single Pass Classification: The initial loop extracts only the necessary information for letter logs, avoiding any unnecessary processing of digit logs at this stage.

  • Targeted Sorting: Sorting is performed exclusively on the subset of logs that require ordering (the letter logs). Digit logs bypass the sorting step entirely, reducing the amount of data the sorting algorithm must handle.

  • Tuple Construction for Direct Comparison: By storing (content, id) tuples, the built-in sort can compare elements without additional function calls or custom comparator logic, leveraging Python’s highly optimized tuple comparison.

  • Generator Yielding: The method yields results incrementally rather than constructing a full list before returning. This lazy evaluation can reduce memory pressure when the caller consumes the generator lazily, and it eliminates the need for an intermediate list allocation.

  • Minimal String Operations: The split operation is performed only once per letter log, extracting both the identifier and the content in a single step. No further slicing or concatenation occurs until the final yield, where the identifier and content are recombined with a single string concatenation.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big box filled with lots of mixed up index cards. Each card has a name at the front and a message on the back. Some of the messages are written with letters and some are written with numbers.

The computer looks at every card one by one. If a card ends with a letter, the computer takes it out and puts it into a special stack for letters. To keep things neat, the computer sorts these letter cards using the words on the back so that they are in a nice alphabetical order just like in a bookshelf. Whenever two cards have the exact same message, the computer looks at the names on the front to decide which one comes first. The computer then puts those sorted cards in a row.

After all the letter cards are organized, the computer goes back to the pile to find all the cards that have numbers on them instead of words. Since the numbers do not need any special sorting, the computer just grabs them in the very same order they were in at the start. These number cards are placed in a line right behind the letter cards to finish the whole project.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 6 | μ = 5.69 | σ = 1.79

Complexity Analysis

Time: loglinear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python Go Rust TS
LeetcodeHelp C++ Java Python
MemoryLimitExceeded C++ Python
Progiez C++ Java Python
github BigEggStudy C#
DimitrisJim C
everthis JS
fartem Ruby
fsq C++
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
lzl124631x C++
martianoff Scala
qiyuangong Java
suxrobGM C#
varunu28 Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
BigEggStudy C#
DimitrisJim C
everthis JavaScript
fartem Ruby
fsq C++
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
lzl124631x C++
martianoff Scala
qiyuangong Java
suxrobGM C#
varunu28 Java
34 links | 19 authors | 11 languages

Videos

9 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

2 hard
3 solutions   May 28, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality