Problem overview
This is the first version of a small sort command-line tool. The method sortLines receives a vector<string> and returns one string: the lines in ascending order, separated by \n. Duplicates stay, and an empty vector gives the empty string.
The order is by character code, as in LC_ALL=C sort. Uppercase letters come before lowercase ones, so "Zebra" sorts before "apple", and an empty line sorts first. With {"banana", "apple", "cherry"} the function returns "apple\nbanana\ncherry".
Approach
There are two jobs: put the lines in order, then join them into one string. The standard library does the first. std::sort from <algorithm> compares std::string values with operator<, which compares them character by character using the character codes. That is exactly the order the lesson asks for, so no custom comparison is needed.
C++ has no built-in way to join strings with a separator, so the second job is a loop that appends each line to a result string and puts a newline in front of every line except the first. That "separator before every item but the first" pattern gives no newline at the start and none at the end.
Other containers could keep lines ordered as you insert them. A multiset<string> does, and unlike a plain set it keeps duplicates. A vector and one call to sort is simpler here, because all the lines arrive at once and the result is built from a vector anyway.
The comparison does not depend on the machine's language settings. std::string compares raw character codes, which is why the lesson describes the behaviour of LC_ALL=C sort and not of a sort that follows dictionary rules for a locale.
Step by step
- Copy the vector. The parameter
linesis already a copy of the caller's vector, since it is passed by value. The lesson still copies it intosortedLines, which keeps the original order available under its own name. - Sort the copy in place.
sorttakes the range to reorder:begin()toend(). - Create an empty
resultstring to build the output in. - Loop over the positions from 0 to
sortedLines.size() - 1. - Add a newline before every line except the first, by testing
i > 0. - Append the line
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());
string result;
for (int i = 0; i < sortedLines.size(); i++) {
if (i > 0) result += "\n";
result += sortedLines[i];
}
return result;
}
};
A few details are worth knowing:
- The range is half-open.
end()points one past the last element, sosort(v.begin(), v.end())sorts the whole vector. - Strings compare by character code. With the default
operator<,"Zebra"is smaller than"apple"because'Z'is 90 and'a'is 97. A shorter string that is a prefix of a longer one comes first, and""is smaller than everything else. - Numbers sorted as text. The lines are strings, so
{"10", "9", "1"}becomes"1\n10\n9":'1'is smaller than'9', so"10"comes before"9". Sorting by numeric value is a different task. size()is unsigned. The loop compares anintwithsortedLines.size(), which is an unsigned type. That is fine here becauseinever goes below 0, but it is the reasonv.size() - 1wraps around to a huge number on an empty vector.sortis not stable. Equal strings are indistinguishable, so it doesn't matter here.
Complexity
Sorting n lines takes O(n log n) comparisons, and each comparison can cost up to the length of the shorter string. Building the result touches every character once, which is linear in the total text size. The copy and the result string need extra space proportional to the input.
Why copy first?
Sorting in place changes the vector it is given. Working on sortedLines instead of lines makes it clear which vector is the sorted one and leaves lines in its original order if you later need it, for example to compare before and after. Because lines is passed by value, the caller's own vector would be safe either way. For a large vector you would normally pass it by reference to avoid the copy, but the lesson's signature takes it by value.
Edge cases and common mistakes
- An empty vector. The loop never runs and the function returns
"". - Empty lines. An empty string sorts first.
{"apple", "Zebra", ""}becomes"\nZebra\napple", which starts with a newline because the first line is empty. - Duplicates.
{"b", "a", "b"}gives"a\nb\nb": all copies are kept. - A trailing newline. Adding
"\n"after every line instead of before all but the first produces an extra newline at the end and fails the tests. - Sorting with a hand-written loop. Writing your own bubble sort works but is slower and easier to get wrong.
std::sortis the idiomatic tool.
Testing
Try these inputs in the editor above. The results are the strings the function returns, with each newline written as \n:
| lines | result |
|---|---|
{"banana", "apple", "cherry"} | "apple\nbanana\ncherry" |
{"apple", "Zebra", ""} | "\nZebra\napple" |
{"b", "a", "b"} | "a\nb\nb" |
{"10", "9", "1"} | "1\n10\n9" |
{} | "" |
The next version builds on this one.
