Problem overview
The last wc version combines the earlier counters. wc(lines: List[String], mode: String): String takes the lines and a mode, and returns the requested count as a string:
"l"gives the number of lines;"w"gives the number of words;"c"gives the number of characters (the sum of the line lengths, with no newlines);"all"gives all three, separated by tab characters: lines, words, characters.
Any other mode gives the same result as "all", and modes are case-sensitive, so "L" is not "l". For ["hello", "world"] with mode "all" the result is "2\t2\t10": two lines, two words and ten characters. For an empty list, "l", "w" and "c" each give "0", and "all" gives "0\t0\t0".
Approach
The word count and the character count both need a pass over the lines, and the line count is just the size of the list. Instead of looping once per mode, the function computes all three numbers in a single pass and only afterwards looks at mode to decide which to return. That keeps the loop free of mode checks.
The branching comes last as a chain of early returns. Three if statements handle "l", "w" and "c". If none of them fires, execution reaches a final line that builds the combined string. That final line handles "all" and every unknown mode with no extra code, which is exactly the behaviour the statement asks for.
Every count must be converted to a string, because the function returns a String. toString does that for an Int.
Step by step
- Count the lines with
lines.lengthin avalnamednumLines. No loop is needed. - Create
numWordsas avarstarting at 0. - Create
numCharsthe same way. - Loop over the lines with
for (line <- lines). - Trim the line into
trimmed, so that blank lines and surrounding spaces don't produce empty pieces when splitting. - Add the words when
trimmed.nonEmpty, usingsplit("\\s+").lengthas in the word-counting version. - Add the characters with
line.length, using the original line (not the trimmed one), because spaces count as characters. - Return the line count as text when the mode is
"l". - Return the word count as text when the mode is
"w". - Return the character count as text when the mode is
"c". - Return all three joined by tabs on the last line, which every other mode reaches.
The solution in Scala
class Solution {
def wc(lines: List[String], mode: String): String = {
val numLines = lines.length
var numWords = 0
var numChars = 0
for (line <- lines) {
val trimmed = line.trim
if (trimmed.nonEmpty) { numWords += trimmed.split("\\s+").length }
numChars += line.length
}
if (mode == "l") { return numLines.toString }
if (mode == "w") { return numWords.toString }
if (mode == "c") { return numChars.toString }
return s"$numLines\t$numWords\t$numChars"
}
}
Language details:
- In Scala,
==on strings compares their contents, somode == "l"is the right test. There is no need forequals. s"$numLines\t$numWords\t$numChars"is an interpolated string: each$nameis replaced by the value, and\tis a real tab. Numbers are converted to text automatically here.- The early
returnstatements leave the method at once, so the later lines run only when the earlier tests failed. - The word count uses
"\\s+", with the backslash doubled because it sits inside a Scala string literal.
Complexity
The loop visits each line once. Trimming and splitting a line takes time proportional to its length, so the total time is proportional to the number of characters in the input. Only a few integers are kept, so the extra space is small, apart from the temporary array that split creates for one line at a time.
Computing all three counts even when the mode asks for one is a deliberate trade. The extra work is small, and the function stays short: the loop does the counting and the branches only choose what to return.
Edge cases and common mistakes
- Returning a number. The signature says
String, soreturn numLineswould not compile. Convert withtoString. - Counting characters from the trimmed line. That drops spaces that belong in the count.
- Treating unknown modes as an error. The rule is that they behave like
"all", and the final return gives that for free. - Ignoring case-sensitivity.
"L"and"x"fall through to the tab-separated result. - Separating with spaces. The combined string uses tab characters, not spaces.
Why the empty list works
With an empty list the loop body never runs, so numWords and numChars keep their starting value of 0, and numLines is 0 as well. Every mode therefore returns zeros without any special case in the code. The same holds for a list of blank lines: they add to the line count, but no words are counted for them.
Testing
Results for List("hello", "world") with each mode (a tab is written as \t):
| Mode | Result |
|---|---|
"l" | "2" |
"w" | "2" |
"c" | "10" |
"all" | "2\t2\t10" |
"x" | "2\t2\t10" |
"L" | "2\t2\t10" |
For an empty list with mode "all" the result is "0\t0\t0". For List(" two words ", "", "a") with "all" it is "3\t3\t13": three lines, three words, and 13 characters (12 + 0 + 1) because the surrounding spaces are counted.
