Problem overview
The method uniqCount takes a List<String> of lines and collapses every run of adjacent duplicates into one output line: the run's length, then the line's text. Each output line is built as String.format("%7d %s", count, value), which is the count right-aligned in 7 characters, a single space, then the value. The output lines are joined with \n. This is the -c flag of the Unix uniq command.
For ["a", "a", "b", "c", "c", "c"] the output, printed, is:
2 a
1 b
3 c
The runs are two "a"s, one "b" and three "c"s, so there are three output lines.
Approach: track the current run
The earlier version only needed to know whether a line differed from the last one kept. Here the length of each run matters, so the method keeps two variables that describe the run the loop is currently in: prev, the text of the run, and count, how many lines it has so far.
For each line there are two cases:
- The line equals
prevand a run is going: the run grows, socountgoes up by 1. - Otherwise, the old run has just ended. If there was a run, write its output line. Then start a new run with this line,
prev = lineandcount = 1.
A run is written only when something different follows it. The last run has nothing after it, so the loop never writes it, and the method must write it once more after the loop.
Here is the state after each iteration for the example, from a real run:
| i | line | count | prev | output lines written so far |
|---|---|---|---|---|
| 0 | a | 1 | a | 0 |
| 1 | a | 2 | a | 0 |
| 2 | b | 1 | b | 1 |
| 3 | c | 1 | c | 2 |
| 4 | c | 2 | c | 2 |
| 5 | c | 3 | c | 2 |
After the loop, count is 3 and prev is c, with two output lines written. The final run is still unwritten. The after-the-loop step adds 3 c as the third.
Step by step
- Create
result, an emptyArrayListin aList<String>variable. It holds one output line per run. - Create
count, anintstarting at 0. Zero means no run has started yet. - Create
prev, aStringset tonull, meaning no text yet. - Loop with an index from 0 while
i < lines.size(). - Test for a continuing run:
count > 0 && lines.get(i).equals(prev), with anelsebranch for everything else. - Continue the run: in the
ifbranch,count++. - Check whether a run just ended: in the
elsebranch, an innerif (count > 0). For the very first linecountis still 0, so nothing is written for a run that does not exist. - Write the finished run: inside that
if, addString.format("%7d %s", count, prev)toresult. - Start the next run: after the inner
if, setprevtolines.get(i), because the line that ended the old run is the first of the new one. - Set
count = 1, since the new run has one line so far. - Flush the last run after the loop with the same test,
if (count > 0). - Write it inside that
ifwith the sameString.formatcall. - Join and return with
String.join("\n", result).
The solution in Java
class Solution {
public String uniqCount(List<String> lines) {
List<String> result = new ArrayList<>();
int count = 0;
String prev = null;
for (int i = 0; i < lines.size(); i++) {
if (count > 0 && lines.get(i).equals(prev)) {
count++;
} else {
if (count > 0) {
result.add(String.format("%7d %s", count, prev));
}
prev = lines.get(i);
count = 1;
}
}
if (count > 0) {
result.add(String.format("%7d %s", count, prev));
}
return String.join("\n", result);
}
}
The Java details worth a closer look:
- The format string.
%7dprints an integer padded with spaces on the left to a width of 7, and%sprints a string.String.format("%7d %s", 3, "c")gives" 3 c": six spaces, the digit, a space and the letter. - Width is a minimum. A count with more than 7 digits is not cut. A run of 12,345,678 lines of
zgives"12345678 z". A count of 12 gives" 12 a". prevstarts asnull.lines.get(i).equals(prev)is safe even then, because the receiver is a real string andequals(null)returns false. Thecount > 0test comes first anyway, which makes the intent clear.- Why flush after the loop. The in-loop write fires when a different line arrives. After the last line nothing arrives, so a second copy of the write is needed.
- Imports. A standalone file needs
import java.util.*;.
Complexity
Time: O(m), where m is the total number of characters: each line is compared once with prev, and each run is formatted once.
Space: O(n + m). The result list has one string per run, and the joined result is a new string.
Edge cases and common mistakes
- An empty list. The loop does not run,
countis 0, and the finalifis skipped. The result is"". - One line.
["x"]gives" 1 x". - Forgetting the last run. Without the code after the loop, the output for the example would stop after
band losec. - Not adjacent.
["a", "b", "a"]gives" 1 a\n 1 b\n 1 a": the twoas are separate runs. - Empty lines.
["", "", ""]gives" 3 ", a count, a space and nothing after it. - Resetting
countto 0. After a new run starts, the count is 1, not 0. With 0 every run would be one short. - Using
==. Strings are compared withequals.
Testing
["a", "a", "b", "c", "c", "c"]gives" 2 a\n 1 b\n 3 c".[]gives"".["x"]gives" 1 x".["a", "b", "a"]gives" 1 a\n 1 b\n 1 a".- Twelve copies of
"a"give" 12 a".
