Problem overview
This is the first version of a small model of the Unix wc command, which counts things in text. The method countLines(List<String> lines) returns the number of lines as an int. Every entry of the list is one line, even an empty string, and an empty list has 0 lines.
For ["hello", "world", "foo", "bar", "baz"] the result is 5.
Approach: ask the list
A list already knows how many entries it holds, so there is nothing to loop over. The size() method returns that count in constant time. The lesson's rule that a blank line still counts is what makes this correct: the method never looks at what the lines contain, only at how many there are.
The longer way is a loop with a counter that adds 1 for every entry. It gives the same answer, but it repeats work the list has already done, and it invites mistakes such as skipping blank lines. Using size() is shorter and can't go wrong in that way.
This lesson has only one line of code on purpose. It introduces a series of small command-line tools, each built from a few list and string operations, and the first one is deliberately as simple as possible.
Step by step
- Return the size. Return
lines.size(). Its type isint, which matches the method's return type.
The solution in Java
class Solution {
public int countLines(List<String> lines) {
return lines.size();
}
}
The Java details worth a closer look:
size()againstlengthandlength(). Collections such asListuse the methodsize(). Arrays have a field,length, with no parentheses, and strings have a method,length(). Mixing them up is a compile error.- Entries, not characters.
size()counts elements. A list with two entries,"a"and"b", has size 2, however long the strings are. - Empty strings count. An entry
""is an element of the list like any other, so["", ""]has size 2. - A newline inside an entry doesn't split it. The list
["a\nb"]has size 1. In this tool, every entry is already one line, and the method counts entries.
The type List<String> is an interface, so the same method works whether the caller passes an ArrayList, a LinkedList or the result of List.of(...). All of them answer size() in the same way.
Complexity
Time: O(1). For the common list types, such as ArrayList and LinkedList, size() returns a stored count and doesn't visit the elements.
Space: O(1). Nothing is allocated.
Edge cases and common mistakes
- Empty list. The result is 0.
- A
nulllist. Callingsize()onnullthrows aNullPointerException. The lesson always passes a real list, possibly an empty one, so the method doesn't check for it. - Blank lines. Skipping empty strings in a loop would undercount:
["", ""]must give 2. - Using
lengthorlength(). Neither exists on aList, so the code doesn't compile. - Counting newline characters. That is a different count. Here, the number of lines is the number of entries.
Testing
The results below come from running the solution:
["hello", "world", "foo", "bar", "baz"]gives5.["", ""]gives2.[]gives0.["a\nb"]gives1.
