#937

Reorder Data in Log Files

Medium
ArrayStringSortingSortingArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(n)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

We can achieve a more efficient solution by using a single pass to classify the logs and then sorting only the letter-logs. This reduces time complexity significantly.

⚙️

Algorithm

5 steps
  1. 1Step 1: Create two lists for letter-logs and digit-logs.
  2. 2Step 2: Iterate through the logs, classifying each log as a letter-log or digit-log.
  3. 3Step 3: Sort the letter-logs based on their contents and identifiers using a custom sorting function.
  4. 4Step 4: Concatenate the sorted letter-logs with the digit-logs.
  5. 5Step 5: Return the final ordered list of logs.
solution.py12 lines
1def reorderLogs(logs):
2    letter_logs = []
3    digit_logs = []
4
5    for log in logs:
6        if log.split()[1].isdigit():
7            digit_logs.append(log)
8        else:
9            letter_logs.append(log)
10
11    letter_logs.sort(key=lambda x: (x.split()[1:], x.split()[0]))
12    return letter_logs + digit_logs

Complexity note: The sorting of letter-logs is O(n log n), and since we are using additional space for storing logs, the space complexity is O(n).

  • 1Letter-logs must be sorted based on content and identifier.
  • 2Digit-logs retain their original order.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.