Problem overview
This version of SortLines takes a List<string> and returns the lines in descending order by character code, joined with "\n". It is the exact reverse of the previous lesson's order, like LC_ALL=C sort -r, so lowercase letters come before uppercase ones. Duplicates are kept, and an empty list gives "".
For ["banana", "apple", "cherry"] the result is "cherry\nbanana\napple".
Approach: swap the arguments of the comparison
A sort asks a comparison function one question over and over: given a and b, which comes first? The answer is a number. Negative means a first, positive means b first, and zero means they tie.
string.Compare(a, b, StringComparison.Ordinal) gives that answer for ascending order. To sort descending, ask the same question with the two strings swapped: string.Compare(b, a, StringComparison.Ordinal). Whenever a is bigger, the swapped call returns a negative number, so a goes first.
Here is one comparison traced. The sort is deciding between a = "cherry" and b = "apple". The lambda evaluates string.Compare("apple", "cherry", StringComparison.Ordinal). a comes before c in character code, so the result is negative, and "cherry" is placed first. For a = "apple" and b = "cherry" the result is positive, so "cherry" is again placed first. Whichever order the sort asks in, the larger string wins.
The lesson passes this comparison to Sort as a lambda, a small unnamed function written inline.
Step by step
- Copy the input into
sortedLineswithnew List<string>(lines). Sorting happens in place, and the copy keeps the caller's list in its original order. - Sort with a lambda.
(a, b) => string.Compare(b, a, StringComparison.Ordinal)takes two lines and compares them the other way round.StringComparison.Ordinalmakes the comparison use character codes, as in the previous lesson, instead of culture rules. - Return
string.Join("\n", sortedLines).
The solution in C#
class Solution {
public string SortLines(List<string> lines) {
List<string> sortedLines = new List<string>(lines);
sortedLines.Sort((a, b) => string.Compare(b, a, StringComparison.Ordinal));
return string.Join("\n", sortedLines);
}
}
With character codes, "apple" is greater than "Zebra", because a (97) is greater than Z (90). That is why lowercase words come first in this order.
The C# details:
- Two ways to say "ordinal". Last lesson used the comparer object
StringComparer.OrdinalwithSort. Herestring.Comparetakes the enum valueStringComparison.Ordinal. Both mean "compare by character code". - The lambda is a
Comparison<string>.List<T>.Sorthas an overload that accepts such a function, and the compiler infers thataandbare strings. - Don't subtract to compare. For numbers,
b - acan overflow for largeintvalues and give the wrong sign. For strings the question doesn't arise, sincestring.Comparedoes the work. - Ties. Equal strings compare as 0, and the order of equal strings is invisible.
Complexity
Time: O(n log n) comparisons for n lines, each comparison costing up to the length of the common prefix. Space: O(n) for the copy and the result.
Edge cases and common mistakes
- Empty list. The result is
"". - Empty lines. In descending order they go last:
["apple", "Zebra", "", "apple"]gives"apple\napple\nZebra\n", which ends with a newline because the final line is empty. - Sorting ascending, then reversing. That also works, but the swapped comparison does it in one step.
- Forgetting
StringComparison.Ordinal.string.Compare(b, a)alone uses the current culture's rules, so mixed-case input could come out in a different order. - Sorting the caller's list. Without the copy, the caller's list would be reordered too.
Testing
["banana", "apple", "cherry"]gives"cherry\nbanana\napple".["apple", "Zebra", "", "apple"]gives"apple\napple\nZebra\n".[]gives"".
