Skip to main content
Back to problems
#937
Medium Algorithms

Reorder data in log files

Array String Sorting
56.9% acceptance
Feb 25, 2026
2194
4421
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 (except the identifier) consist of lowercase English letters. Digit-logs: All words (except the identifier) consist of digits. Reorder these logs so that: The letter-logs come before all digit-logs. The letter-logs are sorted lexicographically by their contents. If their contents are the same, then sort them lexicographically by their identifiers. The digit-logs maintain their relative ordering. Return the final order of the logs.

Solution

Rust
Time O(n log n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn reorder_log_files(logs: Vec<String>) -> Vec<String> {
    let mut letters: Vec<String> = Vec::new();
    let mut digits: Vec<String> = Vec::new();
    for log in logs {
      let rest = log.splitn(2, ' ').nth(1).unwrap_or("");
      if rest.chars().next().map_or(false, |c| c.is_ascii_digit()) {
        digits.push(log);
      } else {
        letters.push(log);
      }
    }
    letters.sort_by(|a, b| {
      let split_a: Vec<&str> = a.splitn(2, ' ').collect();
      let split_b: Vec<&str> = b.splitn(2, ' ').collect();
      let (id_a, rest_a) = (split_a[0], split_a.get(1).copied().unwrap_or(""));
      let (id_b, rest_b) = (split_b[0], split_b.get(1).copied().unwrap_or(""));
      rest_a.cmp(rest_b).then(id_a.cmp(id_b))
    });
    letters.extend(digits);
    letters
  }
}