Problem overview
The method countChars(lines) takes an array of strings and returns the total number of characters in all of them, as an integer. This is a simplified take on the character count of the Unix wc tool. The newlines that would separate the lines in a file are not counted: the answer is just the sum of the line lengths. Spaces and tabs inside a line count as one character each.
For ["hello", "world"] both lines have 5 characters, so the result is 10. An empty line adds 0, and an empty array gives 0. The input is plain ASCII text.
Approach: add up the lengths
There is nothing to parse here. Each string already knows its length, so the job is a running total: start at zero, visit each line once, add its length, and return the total. Because the newline separators are not counted, there is no "plus one per line" adjustment to make.
This is the same loop shape as the word counter before it, with a simpler body. That is deliberate: the next version combines the line, word and character counts in one function, so having each piece as a small loop makes combining them easy.
Step by step
- Create
totalwithletand start it at 0. It changes as lines are read, so it needsletand notconst. - Write a
for...ofloop that names each entry oflinesasline. - Add
line.lengthtototalinside the loop. Whitespace inside the line is part of its length, so no cleaning is needed. - Return
totalafter the loop, so the return runs once, when every line has been counted.
The solution in JavaScript
class Solution {
countChars(lines) {
let total = 0;
for (const line of lines) {
total += line.length;
}
return total;
}
}
Notes on the language:
lengthon a string is a property, not a method: writeline.length, with no parentheses.- JavaScript strings are sequences of UTF-16 code units, and
lengthcounts those. For plain ASCII text, which is all this lesson uses, one character is one unit. Characters outside that range, such as many emoji, can take two units and so count as 2. - A tab character (
"\t") is one character, the same as a space.
Complexity
Reading length is a constant-time operation, so the loop does one step per line: time is O(L) for L lines, and extra space is O(1), just the total.
Edge cases and common mistakes
- Counting the separators. Adding 1 per line for a newline gives the wrong answer here; the convention is lines only.
- Trimming the lines. Leading and trailing spaces are characters too.
["a b", "\tx", ""]gives 5, because the tab counts. - Writing
length(). That is a type error at run time, sincelengthis a number. - Returning inside the loop, which would report only the first line.
Testing
| lines | result |
|---|---|
["hello", "world"] | 10 |
["a b", "\tx", ""] | 5 |
[] | 0 |
