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 "%7d %s".format(count, value): a 7-character right-aligned count, a single space, then the line value. Join all output lines with \n.
Function signature:
fun uniqCount(lines: List<String>): String
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
var prev and var count. When a NEW value comes in (or you reach end), flush the previous run with "%7d %s".format(count, prev) and reset.
Don't forget to flush AFTER the loop too. Use
== for the string comparison.
if (count > 0 && lines[i] == prev) {
count++
} else {
if (count > 0) {
result.add("%7d %s".format(count, prev))
}
prev = lines[i]
count = 1
}
The full solution:
class Solution {
fun uniqCount(lines: List<String>): String {
val result = mutableListOf<String>()
var count = 0
var prev: String? = null
for (i in lines.indices) {
if (count > 0 && lines[i] == prev) {
count++
} else {
if (count > 0) {
result.add("%7d %s".format(count, prev))
}
prev = lines[i]
count = 1
}
}
if (count > 0) {
result.add("%7d %s".format(count, prev))
}
return result.joinToString("\n")
}
}
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
