Build a version of the Unix uniq -d command. Given a list of lines, output only the values whose adjacent run length is greater than one — i.e. lines that actually repeat back-to-back. Each surviving value is printed once (no count, just the value), joined by \n.
Function signature:
uniqDups(lines: string[]): string
Example:
Input: lines = ["a", "a", "b", "c", "c", "c"] Output: "a\nc" When printed: a c
The run of "a"s has length 2 and the run of "c"s has length 3, so both survive. The single "b" is dropped.
Same scaffolding as
uniq -c: track prev and count, flush when the value changes (or you reach the end). The only difference is the filter: only flush if count > 1, and push just the value (no count).
if (count > 1) {
result.push(prev);
}
Remember to flush AFTER the loop too.
The full solution:
class Solution {
uniqDups(lines: string[]): string {
let result: string[] = [];
let count = 0;
let prev: string | null = null;
for (let i = 0; i < lines.length; i++) {
if (count > 0 && lines[i] === prev) {
count++;
} else {
if (count > 1) {
result.push(prev);
}
prev = lines[i];
count = 1;
}
}
if (count > 1) {
result.push(prev);
}
return result.join("\n");
}
}
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
