Build a version of the Unix uniq -u command. Given a list of lines, output only the values whose adjacent run length is exactly one — i.e. lines that did NOT repeat back-to-back. Surviving values are joined by \n.
Function signature:
uniqOnce(lines)
Example:
Input: lines = ["a", "a", "b", "c", "c", "c"] Output: "b" When printed: b
The two "a"s and the three "c"s are dropped because their runs are longer than 1. Only the lone "b" survives.
Same scaffolding as
uniq -d, but the filter flips: flush prev only when count === 1.
if (count === 1) {
result.push(prev);
}
Don't forget to flush AFTER the loop too.
The full solution:
class Solution {
uniqOnce(lines) {
let result = [];
let count = 0;
let prev = 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
