Problem overview
The second version of the cat tool adds the -n flag as a new method, numberedCat(List<String> lines). Each line is printed with its 1-based line number first. The number is right-aligned in a field 6 characters wide, followed by a tab character and then the line's text. Blank lines are numbered too, and an empty list gives an empty string. The rows are joined with \n, with no newline after the last one.
For ["hello", "world", "foo"] the result is the string " 1\thello\n 2\tworld\n 3\tfoo", which prints as:
1 hello
2 world
3 foo
Version 1 joined plain lines with String.join; this version has to change each line before joining, so it uses a loop.
Approach: build each row, separate with newlines
Each row depends on two things: the line's text and its position in the list. That calls for a loop over indices rather than over the lines themselves, because the index gives the line number (as i + 1, since the loop counts from 0).
The rows go into a StringBuilder. Appending to a StringBuilder changes one buffer, while += on a String creates a new string every time. The newline between rows follows the rule from the previous version: it goes between two rows, so the first row gets none in front of it, and the last row gets none after it.
For the row itself, String.format builds text from a pattern. The pattern "%6d\t%s" has two placeholders: %6d prints an integer in a field of at least 6 characters, padded with spaces on the left, and %s prints a string. The \t in the pattern is a real tab character.
Step by step
- Create the builder. Declare a
StringBuildernamedsb. It collects the numbered rows. - Loop by position. Write a
forloop withint ifrom 0 whilei < lines.size(). The index serves twice: for the line number and for picking the line. - Separate the rows. At the top of the loop body, append
"\n"wheni > 0, so no row except the first starts without one and no trailing newline appears. - Append the row. Format
i + 1andlines.get(i)with the pattern"%6d\t%s"and append the result. The+ 1turns the 0-based index into a line number. - Return the text. After the loop, return
sb.toString(). This sits outside the loop, because it runs once after every row is in.
The solution in Java
class Solution {
public String numberedCat(List<String> lines) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < lines.size(); i++) {
if (i > 0) sb.append("\n");
sb.append(String.format("%6d\t%s", i + 1, lines.get(i)));
}
return sb.toString();
}
}
The Java details worth a closer look:
- The width in
%6dis a minimum. Numbers with fewer digits are padded on the left; longer numbers are never cut. For example,String.format("%6d\t%s", 1234567, "wide")gives1234567\twide, with all seven digits. Only inputs of a million lines or more make that happen. %sand the line text. The line goes in as it is, including an empty string. A blank line becomes the number, the tab and nothing else.- Autoboxing.
String.formattakesObjectarguments, so theinti + 1is boxed into anIntegerautomatically.%daccepts it. ifwithout braces.if (i > 0) sb.append("\n");controls only that one statement. The next line runs on every iteration.- Escapes in the pattern.
"\t"inside the Java string literal is already a tab by the timeformatsees it; the pattern contains no backslash.
Complexity
Time: O(total length). Each line is visited once, and lines.get(i) is constant time for an ArrayList. Each row costs time proportional to its text plus the few digits of its number.
Space: O(total length) for the builder and the returned string.
A caveat about indexing: for a LinkedList, get(i) walks the list from one end, which would make the loop quadratic. A for-each loop with a separate counter avoids that, but the lesson's input is an ordinary list.
Edge cases and common mistakes
- Starting the numbers at 0. Writing
iinstead ofi + 1numbers the first line 0. - A newline after every row. Appending
"\n"after each row, instead of before every row but the first, adds a trailing newline to the result. - Blank lines.
["a", "", "b"]gives" 1\ta\n 2\t\n 3\tb". The blank line keeps its number and tab. - Empty list. The loop never runs, so the result is
"". - Two digits. From the tenth line on, the padding shrinks. The tenth row of a 12-line input starts with four spaces and
10, so the tabs stay in the same column as before. - Spaces instead of a tab. Typing spaces in the pattern gives output that looks the same on screen but differs in the characters, so the lesson's tests would fail.
Testing
The results below come from running the solution:
["hello", "world", "foo"]gives" 1\thello\n 2\tworld\n 3\tfoo".["a", "", "b"]gives" 1\ta\n 2\t\n 3\tb".[]gives"".- A list of twelve lines,
L1toL12, gives a result that ends with" 10\tL10\n 11\tL11\n 12\tL12".
