There is a coding puzzle I have encountered on one of those sites (I don't recall if it was leetcode or something else) which goes as follows: Given a list of strings, return the lexicographically smallest concatenation that uses each of the strings once. The solution is, on a technical level, fairly simple. You compare 2 strings a
and b
by checking whether ab<ba
(lexicographically), sort the list, concatenate everything.
Now for the actual question: Does this ordering have a name? I tried googling around but never found anything.
There is also a secondary aspect to this, which is: Is it somehow immediately obvious that this is even a strict weak ordering? I certainly didn't think it was. Here is the proof that I came up with to convince myself that it is one:
For any given string s
let |s|
be its length and let s^n
be s
repeated n
times.
If ab<ba
then a^|b|b^|a|<b^|a|a^|b|
(to see this just successively swap neighboring ab
pairs to get a lexicographically increasing sequence that ends in b^|a|a^|b|
). It follows that a^|b|<b^|a|
because they have the same length. The same argument works for >
and =
so we have proven that ab<ba
is actually equivalent to a^|b|<b^|a|
, with the latter clearly defining a strict weak ordering.