Problem overview
The fourth version of the sort project adds the effect of the -k flag. Each line is comma-separated, and every line has at least field fields. A field may be empty, as in "a,,c". The method sortLines(lines: string[], field: number) sorts the lines by the value in the 1-indexed column field, comparing the values as strings by character code. It returns the original lines joined by \n. Lines whose keys are equal keep their input order, and an empty array gives "".
For field = 2 and ["alice,30", "bob,25", "carol,40"], the keys are "30", "25" and "40", so the result is "bob,25\nalice,30\ncarol,40".
Approach: a comparator that extracts the key
Sorting whole lines would order them by their first column. To order by another column, sort() needs a comparator that looks only at the key. For two lines a and b, split each at the commas and take the piece at position field - 1: fields count from 1, positions count from 0. Then compare the two keys.
The comparison must return a negative number, a positive number or zero. The keys are strings, so subtraction is not available. The lesson uses the relational operators, which compare strings by code unit: x < y gives -1, x > y gives 1 and anything else, meaning equal keys, gives 0.
Returning 0 for equal keys is what makes ties keep their input order. Array sorting in modern JavaScript is stable, so two lines that compare as equal are not swapped. The lines "b,1" and "a,1" compared on field 2 stay in the order they came in, even though "a,1" would come first as a whole line.
The key is computed again on every comparison. That keeps the code short, and for line-sized input it is fine.
Step by step
- Start the sort. Create
const sortedLines: string[]from[...lines].sort(...), passing an arrow function ofaandb. The spread copies the array so the caller's array is untouched. Write the closing});right away. - Get the key of
a:const x = a.split(",")[field - 1]. - Get the key of
bthe same way, asy. - Return the comparison:
-1whenxis smaller,1when it is bigger,0otherwise, using two chained? :operators. - Join the sorted lines with
"\n"and return the text.
The solution in TypeScript
class Solution {
sortLines(lines: string[], field: number): string {
const sortedLines: string[] = [...lines].sort((a, b) => {
const x = a.split(",")[field - 1];
const y = b.split(",")[field - 1];
return x < y ? -1 : x > y ? 1 : 0;
});
return sortedLines.join("\n");
}
}
Language details
split(",")keeps empty pieces:"a,,c".split(",")is["a", "", "c"], so an empty field is a valid key, an empty string that sorts before everything else.- The chained
? :reads from left to right: ifx < ythen-1, otherwise ifx > ythen1, otherwise0. - Comparing the keys as strings means
"10"is smaller than"9", because"1"comes before"9". That is what this version asks for. - The arrow function has a block body with braces, so it needs an explicit
return.
Complexity
With n lines, the sort does O(n log n) comparisons. Each one splits two lines, costing time proportional to their lengths, so the total is O(n log n) comparisons times the line length. The copy and the output take O(n) extra space, plus the temporary arrays made by split.
Edge cases and common mistakes
- Off-by-one on the column. Using
fieldinstead offield - 1reads the wrong column, orundefinedpast the last one. - Returning only
-1or1. Without the zero case, equal keys are reported as "greater", so the result no longer reliably keeps ties in input order. - Ties. With
field = 2,["b,1", "a,1", "c,0"]gives"c,0\nb,1\na,1":"b,1"stays ahead of"a,1". - Text order of numbers. With
field = 2,["x,10", "y,9"]stays as it is, because"10"is smaller than"9"as text. - Empty fields. With
field = 2,["a,,c", "b,a,c"]gives"a,,c\nb,a,c": the empty key goes first. - Empty input.
[]gives"".
Testing
| Input | Result |
|---|---|
field = 2, ["alice,30", "bob,25", "carol,40"] | "bob,25\nalice,30\ncarol,40" |
field = 1, ["alice,30", "bob,25", "carol,40"] | "alice,30\nbob,25\ncarol,40" |
field = 2, ["b,1", "a,1", "c,0"] | "c,0\nb,1\na,1" |
field = 2, ["x,10", "y,9"] | "x,10\ny,9" |
field = 2, ["a,,c", "b,a,c"] | "a,,c\nb,a,c" |
