Problem overview
Version 2 of the sort tool adds the -r flag, built in. sortLines takes a vector<string> and returns the lines in descending order by character code, joined with \n. Duplicates stay and an empty vector gives "".
The result is the exact reverse of version 1's order. Lowercase letters now come before uppercase ones, and an empty line comes last. With {"banana", "apple", "cherry"} the function returns "cherry\nbanana\napple".
Approach
Only one thing changes from the previous version: which string goes first. std::sort accepts an optional third argument, a comparison object that answers "should a come before b?". The default is less, which asks a < b. The standard library also provides greater, which asks a > b, so the bigger string goes first and the whole order flips.
Another way to reverse a result is to sort ascending and then call reverse, or to walk the sorted vector backwards while building the output. All of them work. Passing greater says what you mean in one place: sort in descending order.
This is the whole difference between the two versions, and it is a useful habit: when a new requirement only changes the rule of ordering, change the comparison and leave the rest of the code alone.
The joining code does not change. The lines are appended to one string with a newline before every line except the first.
What the comparison object does
A comparison for sort is anything you can call with two elements that returns a bool: true means the first argument must come before the second. greater<string>() is a ready-made one. Three calls give the same descending result on {"banana", "apple", "cherry"}, each ending in "cherry\nbanana\napple":
sort(v.begin(), v.end(), greater<string>());
sort(v.begin(), v.end(), [](const string& x, const string& y) { return x > y; });
sort(v.rbegin(), v.rend());
The second line is the same comparison written as a lambda, which is the form to reach for when the rule is more specific than "bigger first". The third sorts the reversed view of the vector in ascending order, which leaves the vector itself in descending order. The first form is the one to prefer, because it states the intent directly.
A second example
Take {"apple", "Zebra", ""}. In ascending order by character code the lines would be the empty string, "Zebra" and "apple", because an empty string is smaller than any other and 'Z' (90) is smaller than 'a' (97). Descending order is that list backwards: "apple", "Zebra", then the empty string. Joined with newlines the function returns "apple\nZebra\n". Reading it character by character, the text ends right after the second newline, so the third line is empty.
Step by step
- Copy
linesintosortedLines. - Sort with
greater<string>()as the third argument. The parentheses create the comparison object thatsortwill call. - Create an empty
resultstring. - Loop over the positions of
sortedLines. - Put a newline before every line but the first with
if (i > 0). - Append
sortedLines[i]toresult. - Return
resultafter the loop.
The solution in C++
class Solution {
public:
string sortLines(vector<string> lines) {
vector<string> sortedLines = lines;
sort(sortedLines.begin(), sortedLines.end(), greater<string>());
string result;
for (int i = 0; i < sortedLines.size(); i++) {
if (i > 0) result += "\n";
result += sortedLines[i];
}
return result;
}
};
Details that matter in C++:
greater<string>()is an object, not a type name. Writinggreater<string>without the parentheses passes a type wheresortexpects a value, and the code does not compile.- Same comparison, flipped. Strings are compared by character code, so
"abc"is greater than"ab"(the longer one wins when the shorter is a prefix) and"apple"is greater than"Zebra". - Descending is not "ascending, then reversed" for ties. Equal strings look the same, so the difference never shows. With data that carries other fields, as later in this project, the order of equal items would matter, and
sortdoes not promise to keep it. - Not
less_equalorgreater_equal.sortneeds a strict ordering:comp(a, a)must be false. A comparison that returns true for equal elements breaks that rule and can makesortread past the end of the vector.
Complexity
The time is the same as in version 1: O(n log n) comparisons for the sort, each costing up to the length of the shorter string, plus one pass over the text to build the result. The sorted copy and the result string use extra space proportional to the input. Flipping the comparison costs nothing extra: greater does the same single comparison per pair as less, and a comparison sort needs on the order of n log n of them either way.
Edge cases and common mistakes
- Empty input. No iterations, so the function returns
"". - Empty lines come last.
{"apple", "Zebra", ""}gives"apple\nZebra\n". The result ends with a newline because the last line is empty. That is correct, not a stray separator. - Prefixes.
{"ab", "a", "abc"}gives"abc\nab\na": in descending order the longest string with the shared prefix is first. - Duplicates.
{"b", "a", "b"}gives"b\nb\na". - Forgetting the comparison. Without the third argument the lines come out ascending, which is version 1's answer.
Testing
| lines | result |
|---|---|
{"banana", "apple", "cherry"} | "cherry\nbanana\napple" |
{"apple", "Zebra", ""} | "apple\nZebra\n" |
{"b", "a", "b"} | "b\nb\na" |
{"ab", "a", "abc"} | "abc\nab\na" |
{} | "" |
The next version builds on this one.
