Problem overview
The third version of the wc project counts characters. countChars(lines: string[]): number returns the sum of the lengths of all the lines. Newlines between lines are not counted: only the characters inside each line are, and a space or a tab counts as one character like any other.
For ["hello", "world"] the answer is 10, because each line has 5 characters. An empty line adds 0, and an empty array gives 0. The input is plain ASCII text.
Approach
This is the same shape as the word count from the previous version, with a simpler inner step. There is no need to cut the lines into pieces: a string already knows its size through its length property. Visit every line, add its length to a running total, and return the total.
Step by step
- Create the total. Declare
totalwithletand start it at 0, since nothing has been counted yet. - Visit every line with a
for (const line of lines)loop. The next step goes inside it. - Add the line's length.
line.lengthis the number of characters in that one line, sototal += line.lengthgrows the total by exactly that much. - Return the total after the loop. Returning inside the loop would stop after the first line.
The solution in TypeScript
class Solution {
countChars(lines: string[]): number {
let total = 0;
for (const line of lines) {
total += line.length;
}
return total;
}
}
Notes on the language:
lengthis a property, not a method: writeline.length, notline.length(). The same name is used for arrays, which is whylines.lengthis the number of lines andline.lengthis the number of characters.for...ofover an array gives the values themselves. This is different fromfor...in, which gives the indices as strings.- TypeScript infers
numberfortotalfrom the0, so no annotation is needed here. - Strings in JavaScript are made of UTF-16 code units, and
lengthcounts those. For ASCII text that is the same as counting characters. A character outside the basic range, such as an emoji, can count as 2:"😀".lengthis2, while[..."😀"].lengthis1. The lesson's input is ASCII, so this does not come up.
Complexity
The loop visits each line once and reading length takes constant time, so the running time is O(m) for m lines. It does not depend on how long the lines are. The extra space is O(1): one number.
Edge cases and common mistakes
- Counting separators. The real
wcalso counts the newline after each line. This version does not, so addinglines.lengthto the total gives the wrong answer. For["hello", "world"]the answer is10, not12. - Whitespace. Spaces and tabs inside a line count.
"a\tb"has length 3. Do not trim the lines first. - Empty input. An empty line adds 0, and an empty array leaves the total at its starting value of 0.
- Using the wrong length.
total += lines.lengthinside the loop compiles and runs, but it counts lines, not characters.
Testing
| Input | Result |
|---|---|
["hello", "world"] | 10 |
["a b\tc", "", "xy"] | 7 |
[] | 0 |
The next version builds on this one.
