Build a version of the Unix uniq -c command. Given a list of lines, collapse each run of adjacent duplicates into a single output line that shows the run's count followed by the value.
Each output line is formatted as String.format("%7d %s", count, value): a 7-character right-aligned count, a single space, then the line value. Join all output lines with \n.
Function signature:
public String uniqCount(List<String> lines)
Example:
Input: lines = ["a", "a", "b", "c", "c", "c"]
Output (when printed):
2 a
1 b
3 c
The first run is two "a"s, then a single "b", then three "c"s — three output lines.
Track
String prev and int count. When a NEW value comes in (or you reach end), flush the previous run with String.format("%7d %s", count, prev) and reset.
Don't forget to flush AFTER the loop too. Use
.equals() for the string comparison.
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;
}
The full solution:
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);
}
}
Free plan: 30 tutor messages. Premium is unlimited.
