Problem overview
The Unix wc command counts things in a text: lines, words and characters. This first version counts only lines. You write fun countLines(lines: Array<String>): Int, which takes the lines of a text and returns how many there are.
Every entry counts as a line, even an empty string "". For ["hello", "world", "foo", "bar", "baz"] the answer is 5, and for an empty array it is 0.
Approach
The input is already split into lines, one array entry per line. Counting the lines is therefore counting the entries, and an array knows that number. You don't need a loop or a counter variable, and you don't need to look at the text of any line.
Step by step
- Return
lines.size.sizeis a property of every Kotlin array that holds the number of entries. It is anInt, which matches the function's return type.
The solution in Kotlin
class Solution {
fun countLines(lines: Array<String>): Int {
return lines.size
}
}
Calling it on a few inputs:
| lines | result |
|---|---|
arrayOf("hello", "world", "foo", "bar", "baz") | 5 |
arrayOf("", "") | 2 |
arrayOf() | 0 |
arrayOf("one\ntwo") | 1 |
The last row is one entry that happens to contain a newline character. The function counts entries, not newline characters, so it still returns 1.
Kotlin details worth knowing
sizeis a property, not a method. Writelines.size, with no parentheses. Writinglines.size()doesn't compile: the compiler reports thatsizeof typeIntcannot be invoked as a function.Array<String>is notList<String>. They are different types, and Kotlin won't convert one to the other when you call a function. Passing aList<String>where anArray<String>is expected is a compile error (argument type mismatch). Both have asizeproperty, so the body of the function would look the same for either.- Arrays have a fixed size. You create one with
arrayOf(...), and its size never changes afterwards, sosizeis always the number of entries it was created with. count()gives the same number.lines.count()without arguments also returns the number of entries.sizereads the stored value directly, which is why it is the usual choice.- The empty case is automatic. An empty array has a
sizeof 0, so no special branch is needed.
Complexity
Reading size takes constant time, because the array stores its length, and the function uses no extra space. The number of lines doesn't affect the running time.
Edge cases and common mistakes
- Empty strings are lines.
arrayOf("", "")has 2 lines. Don't filter out blank entries before counting. - Newlines inside an entry. The function counts entries. If one entry contains
"\n", it is still one entry here. - Parentheses on
size.lines.size()is a compile error in Kotlin. - Counting by hand. A loop with a counter gives the right answer but adds code and room for off-by-one errors, when the array already holds the number.
- The empty array. The result is
0, not an error and not-1.
Try the cases in the table in the editor above. The next version builds on this function.
