Problem overview
The Unix wc command counts things in its input, and its -l flag counts lines. The function countLines takes a vector<string> of lines and returns how many there are, as an int.
For ["hello", "world", "foo", "bar", "baz"] the answer is 5. Every entry is one line, including an empty string, so ["", ""] has 2 lines. An empty vector has 0 lines.
Approach: ask the vector
A vector always knows how many elements it holds, and its size method returns that number in constant time. No loop or counter variable is needed. Counting the lines is the same as counting the strings, and what the strings contain doesn't matter at all: an empty string, a string with spaces or a long text each count as one.
This is the first version of the wc tool, and the next version builds on it.
Step by step
- Return
lines.size(). The method is a single statement, because the vector already holds the count.
The solution in C++
class Solution {
public:
int countLines(vector<string> lines) {
return lines.size();
}
};
The C++ details worth a closer look:
size()returns an unsigned type. It isvector<string>::size_type, an unsigned integer. The function's return type isint, so the value is converted on return. That is safe for any realistic number of lines. Writingreturn (int)lines.size();would make the conversion visible, and it behaves the same.- Method call syntax.
sizeis a member function, so it needs the parentheses even though it takes no arguments.lines.sizewithout them is a compile error. empty()is a different question.lines.empty()answers "are there no lines?" with abool. The count issize().- The copy. The vector is passed by value, so the call copies the strings before counting them. A
const vector<string>¶meter avoids that, but the lesson uses the plain value.
Complexity
Time: O(1) for the count itself. A vector stores its size, so size() does not walk over the elements. The by-value parameter makes the whole call O(n) in practice, because the vector is copied when the function is called, and that copy comes from the signature, not from the counting.
Space: O(1) beyond the copy. The function creates no containers of its own and returns a single integer.
Edge cases and common mistakes
- Empty vector.
size()is 0, so the answer is 0. - Blank lines count.
["", ""]gives 2. A solution that skips empty strings would give 0. - One line.
["a b c"]gives 1. The words inside a line don't matter for this count. - Writing a loop that counts by hand. It works, but it repeats what
size()already gives and adds room for an off-by-one error. Aforloop is only needed when each line must be inspected. - Counting characters instead. Summing the lengths of the strings counts characters, not lines.
Testing
Each result is the function's output:
["hello", "world", "foo", "bar", "baz"]gives5.["", ""]gives2.["a b c"]gives1.[]gives0.
