Build the next version of the Unix sort command, this time with the -n flag baked in. Each input line is the string form of an integer that fits in 32 bits (an optional leading -, no leading +; leading zeros such as "007" are allowed). Sort the lines numerically (not lexicographically) in ascending order, and return the original strings joined by newlines (\n). Lines with the same numeric value keep their original relative order (a stable sort). The real sort -n would break such ties by comparing the text; this version does not. If the list is empty, return the empty string.
Note: lexicographic sort would put "100" before "20"; numeric sort puts 20 before 100.
Function signature:
public string SortLines(List<string> lines)
Example:
Input: lines = ["100", "20", "3", "10"] Output: "3\n10\n20\n100" When printed: 3 10 20 100
Reorder with LINQ's
OrderBy (a stable sort, unlike List.Sort), keyed on int.Parse of each string, then turn it back into a list. The strings themselves stay unchanged.
The full solution:
class Solution {
public string SortLines(List<string> lines) {
List<string> sortedLines = new List<string>(lines);
sortedLines = sortedLines.OrderBy(s => int.Parse(s)).ToList();
return string.Join("\n", sortedLines);
}
}
Free plan: 30 tutor messages. Premium is unlimited.
