Skip to main content

937. Reorder Data in Log Files

medium

Sort an array of logs where letter-logs go first (lexicographic by content then identifier) and digit-logs keep relative order. A custom-key sort with a tuple tiebreaker.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

You are given an array of logs. Each log is a space-delimited string of words, where the first word is the identifier. There are two types of logs: letter-logs (all words after the identifier consist of lowercase English letters) and digit-logs (all words after the identifier consist of digits). Reorder these logs so that: (1) all letter-logs come before any digit-log; (2) letter-logs are sorted lexicographically by their contents — if contents are the same, then sort by identifier; (3) digit-logs maintain their relative ordering. Return the final order of the logs.

Constraints

  • 1 <= logs.length <= 100
  • 3 <= logs[i].length <= 100
  • All the tokens of logs[i] are separated by a single space.
  • logs[i] is guaranteed to have an identifier and at least one word after the identifier.

Examples

Example 1

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"]

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Hints

Progressive — try the first before opening the next.

Hint 1

Split each log into identifier and content. Classify by whether the first content character is a digit.

Hint 2

Use a stable sort with a key that puts digit-logs after letter-logs.

Hint 3

Key for letter-logs: (0, content, identifier). Key for digit-logs: (1,) so they all tie and the stable sort preserves their order.

Solution approach

Reveal approach

Stable sort with a tuple key. For each log, split into identifier and rest at the first space. If rest[0] is a digit, the key is (1,) — all digit-logs tie and the stable sort keeps their original order. Otherwise the key is (0, rest, identifier) — letter-logs come first, sorted by content with identifier as tiebreaker. O(n * m log n) time where n = number of logs and m = average log length (string comparison cost). O(n * m) space for the keys and the output.

Complexity

Time
O(n * m log n)
Space
O(n * m)

Related patterns

  • custom-sort
  • string-parsing
  • stable-sort

Related problems

Asked at

Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).

  • Amazon

Practice these live with InterviewChamp.AI

Drill Reorder Data in Log Files and Strings problems under real interview conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →