Skip to the code
cf.
+50 XP

#222 Natural Order for File Names

hard

A file browser should list img2.png before img10.png, the way people expect, not the way plain string sorting does. Split each name into chunks: each chunk is either a run of digits or a run of non-digits. For example, "img10.png" becomes "img", "10", ".png".

Compare two names chunk by chunk from the left. If both chunks are digit runs, compare them by numeric value ("007" equals "7"). Otherwise compare the chunks as plain strings by character codes. The first difference decides. If one name runs out of chunks while all compared chunks were equal, the shorter one comes first. Names that compare equal keep their original order.

Write naturalSort(files) that returns a new array of the names in this order.

Example 1

Input: files = ["img10.png","img2.png","img1.png"]
Output: ["img1.png","img2.png","img10.png"]

The digit chunks compare as numbers: 1 < 2 < 10.

Example 2

Input: files = ["v1.10","v1.9","v1.9a"]
Output: ["v1.9","v1.9a","v1.10"]

v1.9 runs out of chunks first, so it comes before v1.9a; 9 < 10 puts both before v1.10.

Constraints

  • 0 <= files.length <= 10000
  • Names are non-empty ASCII strings.
  • Digit runs have at most 15 digits.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).