Start learning free

LESSON 389 OF 409 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: sort v2 — Reverse (Descending) Sort in C++

Practice

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

    Sort V2 in C++

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