Problem overview
The -n flag of cat puts a line number in front of every line. The function numberedCat takes a vector<string> and returns one string where each row is the 1-based line number, right-aligned in a field 6 characters wide, then a tab character, then the line text. Rows are joined with newlines, with no newline after the last one. The previous version, cat, only joined the lines.
For ["hello", "world", "foo"] the result is " 1\thello\n 2\tworld\n 3\tfoo". Each number is padded on the left with spaces until it is 6 characters wide. Blank lines are numbered like any other, so ["", "x"] gives " 1\t\n 2\tx". An empty vector gives "".
Approach: format each row in a string stream
The structure is the same as in the first version: loop over the positions, put a newline before every row except the first, and append. What is new is the row itself. Building " 1\thello" needs a number padded to a fixed width, which is awkward with plain string operations.
C++ solves it with stream manipulators. An ostringstream is an output stream that collects what you send into it as text, just as cout sends text to the screen. The manipulator setw(6) sets the minimum width of the next value written to the stream, and by default it pads on the left, which right-aligns numbers. After the row is formatted, oss.str() hands over the text as a string.
One thing to know about setw: it applies only to the very next value. That suits this lesson, because the number is the only field that needs padding, and the tab and the line text that follow are written at their natural width.
Step by step
- Create an empty
stringnamedresult. The finished rows are appended to it. - Loop over the positions from 0 while
i < lines.size(). The position gives both the line and its number. - Add the separator. When
iis above 0, append"\n", so rows are separated and the last row has no newline after it. - Create an
ostringstreamnamedossinside the loop, so each row starts with an empty stream. - Write the row into the stream in order:
setw(6), the numberi + 1, a"\t", thenlines[i]. The number isi + 1because lines are numbered from 1 whileistarts at 0. - Append
oss.str()toresult. One finished row joins the others. - Return
resultafter the loop.
The solution in C++
class Solution {
public:
string numberedCat(vector<string> lines) {
string result;
for (int i = 0; i < lines.size(); i++) {
if (i > 0) result += "\n";
ostringstream oss;
oss << setw(6) << (i + 1) << "\t" << lines[i];
result += oss.str();
}
return result;
}
};
The C++ details worth a closer look:
- Headers.
ostringstreamcomes from<sstream>andsetwfrom<iomanip>. In the lesson they are already included at the top of the file. In a program of your own you must include both. setwis a minimum. A number wider than 6 digits is not cut:setw(6)with 1234567 prints1234567, seven characters. It only adds padding when the value is shorter.- It affects one value. After
setw(6)and a number, the stream goes back to the default width of 0. Writingsetw(3) << "x" << setw(6) << 12producesx 12: each width applies to the single value after it. - Why a new stream per row. The stream is declared inside the loop, so every iteration starts with empty text. A stream declared outside would keep growing and
str()would return all earlier rows again. - The tab is one character.
"\t"is a single tab, not spaces. The number takes 6 columns and the tab comes after them.
Complexity
Time: O(total length). Each line is visited once. Formatting one number takes time proportional to its digits, which grow only logarithmically with the line count, and the line itself is copied once into the stream and once into result.
Space: O(total length). The result holds all rows. The stream for the current row is temporary.
Edge cases and common mistakes
- Empty vector. The loop doesn't run and the function returns
"". - Blank lines are numbered.
["", "x"]gives" 1\t\n 2\tx": the first row is the number and a tab with no text after it. - Starting at 0. Writing
iinstead ofi + 1numbers the first line 0. - Numbers past 6 digits. A number with more than 6 digits makes that row longer than the others, because
setwnever truncates. - A trailing newline. The separator goes before a row (when
i > 0), so the output ends right after the last line's text. - Width of the whole row. The 6 columns cover only the number. The tab and the text come after it.
Testing
Each result is the function's output, with newlines written as \n and tabs as \t:
["hello", "world", "foo"]gives" 1\thello\n 2\tworld\n 3\tfoo".["", "x"]gives" 1\t\n 2\tx".[]gives"".
With ten lines that are all "l", the last row is " 10\tl": the number 10 takes two columns and gets four spaces of padding.
