Given an array of strings strs, sort the strings in natural order (also called human order). In natural order, consecutive digit characters within a string are treated as a single integer for comparison, while non-numeric segments are compared as text.
For example, the lexicographic order of ["item10", "item2", "item1"] is ["item1", "item10", "item2"], but the natural order is ["item1", "item2", "item10"] because the numeric parts 1, 2 and 10 are compared as integers.
Return the strings sorted in natural order. When two strings compare equal under the natural ordering rules, keep their relative input order (stable sort).
Function Signature
def natural_sort(strs: list[str]) -> list[str]:
Rules
-
Split each string into maximal runs. A digit run is a run of the characters
0
to
9
; a text run is a run of any other characters.
-
Compare two strings run by run from the left and stop at the first position where they differ:
-
two text runs compare as strings by character code (ASCII order, so the comparison is case-sensitive and a run that is a prefix of the other comes first);
-
two digit runs compare by integer value, so leading zeros do not matter (
007
equals
7
);
-
a text run comes before a digit run.
-
If every compared run is equal and one string has fewer runs, the string with fewer runs comes first.
-
Strings with equal run lists, such as
"a01"
and
"a1"
, keep their input order.
Constraints
-
1 <= len(strs) <= 10^4
-
1 <= len(strs[i]) <= 100
-
strs[i]
consists of printable ASCII characters.
Examples
Input: strs = ["item10", "item2", "item1", "file20", "file3"]
Output: ["file3", "file20", "item1", "item2", "item10"]
The text run file comes before item. Within each prefix the numbers compare as integers: 3 < 20, and 1 < 2 < 10.
Input: strs = ["a1b2", "a1b10", "a1b1", "a2b1", "a10b1"]
Output: ["a1b1", "a1b2", "a1b10", "a2b1", "a10b1"]
The first numeric runs are 1, 1, 1, 2 and 10. The three strings that start with a1 are then ordered by their trailing numbers 1, 2 and 10.
Input: strs = ["v1", "10", "v01", "v", "2", "v1a"]
Output: ["v", "v1", "v01", "v1a", "2", "10"]
The four strings that start with the text run v come before 2 and 10, which start with a digit run. "v" has the fewest runs, so it leads. "v1" and "v01" have equal runs because 01 and 1 are the same integer, so they keep their input order, and "v1a" has one more run than both. Last, 2 < 10 as integers.