Start learning free

LESSON 22 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Sort V2 in C++: Reverse Order with greater<string>

Practice Read the full explanation

Build the next version of the Unix sort command, this time with the -r flag baked in. Given a list of lines, return them sorted in descending order by character code (the exact reverse of v1's order, like LC_ALL=C sort -r: lowercase letters come before uppercase ones), joined by newline characters (\n). Duplicates are all kept. If the list is empty, return the empty string.

Function signature:

string sortLines(vector<string> lines)

Example:

Input: lines = ["banana", "apple", "cherry"]

Output: "cherry\nbanana\napple"

When printed:
cherry
banana
apple

Pass greater<string>() as the third argument to std::sort for descending order.

The full solution:
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;
    }
};

STEP 1 OF 7
    Ctrl + Enter to check

    C++ · PROJECTS: COMMAND-LINE TOOLS

    Sort V2 in C++, explained

    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

    1. Copy lines into sortedLines.
    2. Sort with greater<string>() as the third argument. The parentheses create the comparison object that sort will call.
    3. Create an empty result string.
    4. Loop over the positions of sortedLines.
    5. Put a newline before every line but the first with if (i > 0).
    6. Append sortedLines[i] to result.
    7. Return result after 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. Writing greater<string> without the parentheses passes a type where sort expects 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 sort does not promise to keep it.
    • Not less_equal or greater_equal. sort needs a strict ordering: comp(a, a) must be false. A comparison that returns true for equal elements breaks that rule and can make sort read 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

    linesresult
    {"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.

    Keep going with C++1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free