1191. Natural Filename Sort

Medium3.5 points estimatedCustom ComparatorSortingString

A photo gallery should list img2 before img10. Given names, return them in natural order. Split every name into maximal chunks of digits and of non-digits, then compare two names chunk by chunk from the left.

A digit chunk sorts before a non-digit chunk. Two digit chunks compare by numeric value (strip leading zeros, the shorter result is smaller, then compare digit by digit); when the values are equal the chunk with fewer leading zeros comes first and the comparison ends there. Two non-digit chunks compare by character codes, so uppercase precedes lowercase and a proper prefix comes first. If every shared chunk is equal, the name with fewer chunks comes first.

Return the sorted array; equal strings simply sit side by side. A comparison sort with an O(L) comparator gives O(n log n * L) time and O(n) extra space, where L is the name length.

Example 1

Input:
names = ["file10","file2","file1"]
Output:
["file1","file2","file10"]
Explanation:

The numbers 1, 2 and 10 are compared by value, so file1 comes first and file10 last.

Example 2

Input:
names = ["img02","img2","img1","img10"]
Output:
["img1","img2","img02","img10"]
Explanation:

Values 1, 2, 2 and 10 order the names, and between img2 and img02 the one with fewer leading zeros comes first.

Example 3

Input:
names = ["a1","a","1a","B2","b"]
Output:
["1a","B2","a","a1","b"]
Explanation:

A digit chunk sorts before a letter chunk, so 1a is first, and a precedes a1 because its chunks are a prefix of a1's.

Constraints

1 ≤ names.length ≤ 5 * 104

1 ≤ names[i].length ≤ 20

names[i] contains only letters and digits

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 6,000 msC++ 1,500 msJava 3,000 msJavaScript 3,000 msTypeScript 3,000 ms

Expected complexity

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

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…