Problem overview
This version of the uniq project imitates uniq -u. The method uniqOnce receives an array of lines and returns a single string that holds only the lines that stand alone, joined with \n. A line stands alone when its run has length exactly one: the lines right before and right after it are different (or it is at an end of the array). Anything that repeats back to back is dropped completely, including its first copy.
For ["a", "a", "b", "c", "c", "c"] the runs are a a, b and c c c. Only the run of b has length one, so the result is "b". The earlier version of this tool already walked through the lines tracking runs; this one changes what is kept.
Approach: track the current run, decide when it ends
The key word is adjacent. The lines are not sorted and not grouped, so you can't count occurrences with a single tally for the whole array. For ["a", "b", "a"] each "a" is alone, because the two copies are separated by "b", and the result is "a\nb\na".
So the code follows one run at a time with two variables: prev, the text of the current run, and count, how many lines it has so far. When the next line equals prev, the run grows. When it differs, the current run is finished, and that is the moment to decide: keep prev if count is 1, then start a new run with the new line.
A run only ends when a different line shows up, and the last run has nothing after it. That is why a second check is needed after the loop. It is the most common mistake in this lesson.
A tempting shortcut is a Map from line to total count, keeping lines whose count is 1. It answers a different question: for ["a", "b", "a"] it would drop both "a"s, while the real command keeps them. The command works on neighbours only, which is why it is usually run on sorted input, where equal lines are already next to each other. This version doesn't sort: it takes the lines in the order given, and the single pass with prev and count needs no extra data structure.
Step by step
- Create
result, an emptystring[]that will collect the surviving lines. - Create
countand start it at 0. Zero means that no run has started. - Create
prev, typedstring | nulland set tonull, so it can say "no line yet". - Loop over the positions of
lineswithi. - Test for a continuing run:
count > 0andlines[i] === prev. Both must hold. The first condition matters for an empty line at the start, as shown in the edge cases below. - In the
ifbranch, add 1 tocount. - In the
elsebranch, a different line has arrived, so the previous run is over. Check whether itscountis 1. At the very first linecountis 0, so nothing is pushed. - Push
prevwhen that check passes. - Start the next run: set
prevtolines[i]. - Set
countto 1, because the new run has one line so far. - After the loop, test
count === 1again, because the last run was never closed by a following line. - Push
prevfor that last run if it is alone. - Return
result.join("\n").joinputs the separator only between elements, so there is no trailing newline, and an emptyresultgives"".
The solution in TypeScript
class Solution {
uniqOnce(lines: string[]): string {
let result: string[] = [];
let count: number = 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");
}
}
Language details
string | nullis a union type:prevholds either text ornull. Types are erased when TypeScript compiles to JavaScript, so at run timeprevis simply a string ornull.===compares strings by content, so two separate string values with the same characters are equal.- The two
if (count === 1)tests are the same on purpose: one closes a run when a different line arrives, the other closes the final run.
Complexity
The loop visits each line once and does constant work per line, so the time is O(n) for n lines (plus the cost of comparing strings and of the final join, which is proportional to the total text). The extra space is the result array, which holds at most n lines.
Edge cases and common mistakes
- Forgetting the last run. Without the check after the loop,
["a", "a", "b"]would return an empty string instead of"b", and["x"]would lose its only line. - Non-adjacent repeats.
["a", "b", "a"]gives"a\nb\na": nothing is dropped, because no run is longer than one. - Every line repeated.
["a", "a"]gives"", and an empty array also gives"". - An empty line first. A line can be the empty string. Because the test is
count > 0 && lines[i] === prev, an input like["", "a", "a", "b"]gives"\nb": the empty line stands alone and is kept. - Keeping one copy of a repeated line. This command is not "remove duplicates". A run of length two or more disappears completely.
Testing
| Input | Result |
|---|---|
["a", "a", "b", "c", "c", "c"] | "b" |
["a", "b", "a"] | "a\nb\na" |
["a", "a", "b"] | "b" |
["a", "b", "b"] | "a" |
["a", "a"] | "" |
[] | "" |
