Problem overview
Version 3 of the sort tool adds the -n flag. Each line of the vector<string> passed to sortLines is the text of a 32-bit integer: an optional leading -, no +, and possibly leading zeros such as "007". The function sorts the lines by numeric value, ascending, and returns the original strings joined with \n.
Lines with the same value keep their input order, so this is a stable sort. An empty vector gives "". For {"100", "20", "3", "10"} the result is "3\n10\n20\n100". Sorted as text, "100" would come before "20", because '1' is smaller than '2'. That is the trap this version is about.
Approach
Keep the strings as they are, because the output must contain them unchanged, "007" included. Change only how two strings are compared: convert each to an int with stoi and compare the numbers. That makes a custom comparison, which sort and stable_sort accept as a third argument.
Converting every line to an int, sorting the numbers and converting back with to_string would lose information: "007" would come back as "7", and the lesson's tests expect the original text. Sorting the strings with a numeric rule avoids the problem.
Stability matters because different strings can have the same value. "7", "007" and "07" all mean 7. The lesson wants them to stay in the order they arrived. std::sort gives no such promise, but std::stable_sort does: elements that compare equal keep their relative order. It has the same interface as sort, so the switch is a single word.
Converting inside the comparison means each string is parsed again every time it is compared. That costs a little extra work per comparison but keeps the code short, and the lines are short.
Step by step
- Copy
linesintosortedLines. - Call
stable_sortover the whole vector with a lambda as the third argument. The lambda takes twoconst string¶meters,aandb, and returnsstoi(a) < stoi(b). It is true whenamust go first. The references avoid copying the strings andconstpromises not to change them. - Create an empty
resultstring. - Loop over the positions of
sortedLines. - Open an
iffori > 0. - Inside it, add a newline to
result, so no newline precedes the first line. - After the
if, appendsortedLines[i], the original text. - Return
result.
The solution in C++
class Solution {
public:
string sortLines(vector<string> lines) {
vector<string> sortedLines = lines;
stable_sort(sortedLines.begin(), sortedLines.end(), [](const string& a, const string& b) {
return stoi(a) < stoi(b);
});
string result;
for (int i = 0; i < sortedLines.size(); i++) {
if (i > 0) {
result += "\n";
}
result += sortedLines[i];
}
return result;
}
};
The details worth knowing:
- A lambda is a function written in place. The
[]is its capture list, which is empty here because the comparison needs nothing from the surrounding code. The parameter list and the body follow it. stoireads decimal. Leading zeros are fine and do not mean octal:stoi("007")is 7. Negative numbers work too:stoi("-20")is -20.stoican throw. A string that does not fit in anint, such as"2147483648", throwsstd::out_of_range, and a string with no digits, such as"abc", throwsstd::invalid_argument. The lesson guarantees 32-bit integers, so neither happens here.- Compare with
<, don't subtract. A comparison likestoi(a) - stoi(b)can overflow for values near the ends of theintrange, and signed overflow is undefined behaviour. It also returns anint, not theboolthe algorithm expects. - Strict ordering. The comparison returns false for equal numbers. That is what lets
stable_sortleave them where they are.
Parsing each string once
If the repeated parsing worried you, you could convert every line once, pair each number with its original text, and sort the pairs on the number:
vector<pair<int, string>> keyed;
for (const string& s : lines) keyed.push_back({stoi(s), s});
stable_sort(keyed.begin(), keyed.end(), [](const auto& a, const auto& b) {
return a.first < b.first;
});
Joining the second fields with the same loop gives "3\n007\n7\n07" for {"007", "7", "07", "3"}, the same answer as the lesson's code. For the short lines in this lesson the simpler version is enough, and it matches the steps above.
Complexity
A stable sort of n lines does O(n log n) comparisons when it can use extra memory, which stable_sort normally does; it falls back to a slower O(n log² n) method if that memory is not available. Each comparison parses two short strings. Building the result is one pass over the text. The extra space is the sorted copy and the result, plus the buffer the stable sort may allocate.
Edge cases and common mistakes
- Sorting as text. A plain
sorton the strings turns{"100", "20", "3", "10"}into"10\n100\n20\n3". The numeric comparison gives"3\n10\n20\n100". - Negative numbers.
{"-5", "3", "-20", "0"}gives"-20\n-5\n0\n3". - Equal values with different text.
{"7", "007", "07"}keeps its order and gives"7\n007\n07". With{"007", "7", "07", "3"}the 3 moves to the front and the three sevens keep their relative order:"3\n007\n7\n07". - The limits of 32 bits.
{"2147483647", "-2147483648", "0"}gives"-2147483648\n0\n2147483647". - Returning the numbers instead of the strings. The output must show each line as it came in, so
"007"stays"007". - Empty input. No lines, no loop, result
"".
Testing
| lines | result |
|---|---|
{"100", "20", "3", "10"} | "3\n10\n20\n100" |
{"-5", "3", "-20", "0"} | "-20\n-5\n0\n3" |
{"007", "7", "07", "3"} | "3\n007\n7\n07" |
{"2147483647", "-2147483648", "0"} | "-2147483648\n0\n2147483647" |
{} | "" |
The next version builds on this one.
