Problem overview
The fourth version of the wc project merges the earlier ones. wc(lines: string[], mode: string): string computes the line, word and character counts and returns the one the mode asks for, as a string:
"l"returns the number of lines."w"returns the number of words."c"returns the number of characters, as the sum of the line lengths with no newlines."all"returns lines, words and characters joined by tab characters.
Any other mode, such as "x" or "L", behaves like "all": modes are case-sensitive. For ["hello", "world"] with mode "all" the result is the string "2\t2\t10". For an empty array, "l", "w" and "c" give "0", and "all" gives "0\t0\t0".
Approach: count everything once, then choose
One option is to branch on the mode first and run only the loop that is needed. The lesson takes a simpler route: compute all three numbers in a single pass, then pick what to return. It costs a little extra work when only one count is wanted, but the code has one loop and the mode check stays at the end, where it is easy to read.
The number of lines needs no loop at all, because it is the array's length. Words and characters are running totals, built exactly as in the previous two versions.
This structure also shows how small programs grow. The three earlier versions each answered one question. Here the same loop bodies share one loop, and the new work is only the decision at the end: which of the stored numbers to hand back, and in what form.
Step by step
numLines. Storelines.lengthin alettypednumber.numWords. Anumberthat starts at 0.numChars. Anothernumberstarting at 0.- Loop over the lines with
for (const line of lines). - Add the words. Trim the line, split on
/\s+/, filter out empty pieces and take thelength. The filter matters because"".split(/\s+/)is[""], one empty piece, which would otherwise count as a word. - Add the characters.
line.lengthincludes spaces and tabs. - Mode
"l". After the loop, returnString(numLines)if the mode is"l". The function returns text, so a number has to be converted. - Mode
"w". The same withnumWords. - Mode
"c". The same withnumChars. - Everything else. The last line returns all three counts joined with tabs. It is reached for
"all"and for any mode that was not matched above, which is exactly what the specification wants.
The solution in TypeScript
class Solution {
wc(lines: string[], mode: string): string {
let numLines: number = lines.length;
let numWords: number = 0;
let numChars: number = 0;
for (const line of lines) {
numWords += line.trim().split(/\s+/).filter(x => x).length;
numChars += line.length;
}
if (mode === "l") { return String(numLines); }
if (mode === "w") { return String(numWords); }
if (mode === "c") { return String(numChars); }
return numLines + "\t" + numWords + "\t" + numChars;
}
}
Language details worth a look:
===compares strings by content, and it is the usual choice in TypeScript.mode === "l"is false for"L", which is why uppercase modes fall through to the last line.String(n)converts a number to its text form. The result type isstring, so returning a bare number would be a type error. The compiler reports it, and the returned value would still be a number at run time, because types are erased, so a test that expects"3"would not get it.- In the last line,
numLines + "\t" + numWords + ...works because+with a string on one side turns the number into text. The first+already has a string on its right, so no numeric addition happens. Be careful when no string is involved:1 + 2 + "\t" + 3gives"3\t3", because the first two numbers are added. "\t"is one tab character, so"2\t2\t10"has three fields.
Tracing one call
Take lines = ["hello world", "foo bar baz", ""] and mode = "w". Before the loop, numLines is 3 and the other two totals are 0. The first line adds 2 words and 11 characters. The second adds 3 words and 11 characters. The empty line adds 0 words, because its split-and-filter chain ends with an empty array, and 0 characters. After the loop the totals are 5 words and 22 characters. The first if fails because the mode is not "l", the second succeeds, and the method returns "5".
Complexity
A single pass over the lines does all the work, and each character is handled a constant number of times, so the time is O(n) for n characters in total. The extra space is O(1) beyond the temporary pieces of one line.
Edge cases and common mistakes
- Returning a number. Each count must go through
String(...). In"all"mode the+operators do it implicitly. - Unknown modes.
"x"and"L"do not raise an error. They produce the same tab-separated text as"all". Checkingmode === "all"and then returning something else for the leftovers would break that rule. - Empty list. The loop never runs, so the counts stay 0:
"l"gives"0"and"all"gives"0\t0\t0". - Blank lines. A blank line still counts as a line in
"l", adds 0 words and adds 0 characters.
Testing
Take lines = ["hello world", "foo bar baz", ""], which has 3 lines, 5 words and 22 characters (11, 11 and 0):
| mode | Result |
|---|---|
"l" | "3" |
"w" | "5" |
"c" | "22" |
"all" | "3\t5\t22" |
"x" | "3\t5\t22" |
With []: mode "l" gives "0" and mode "all" gives "0\t0\t0".
