Problem overview
The method UniqOnce takes a List<string> of lines and imitates uniq -u. It returns one string holding every line that was not repeated right next to itself, with a newline between each two lines.
The key word is adjacent. A line counts as repeated only when the same text appears in consecutive positions. For ["a", "a", "b", "c", "c", "c"] the runs are a a, b and c c c. Only the run of length 1 survives, so the result is "b". Note that a line which appears twice but in different places is not a repeat: ["a", "b", "a"] contains three runs of length 1, and all three lines are kept, giving "a\nb\na".
Approach: measure each run as you walk past it
The input is not sorted and we may not sort it, so we cannot count how often each text occurs overall. Instead, the method walks the list once and keeps two pieces of state that describe the current run:
prev, the text the run is made of;count, how many lines the run has so far.
When the next line equals prev, the run grows. When it differs, the run has ended, and at that moment we know its final length. If the length is exactly 1, the line goes into the result. Then the new line starts a new run.
There is one subtle point: a run only ends when a different line arrives. The last run in the list has no line after it, so the loop never closes it. A second check after the loop handles that run.
Step by step
- Create
result, an emptyList<string>. A list suits this job because its size is not known in advance and it grows withAdd. - Start
countat 0. Zero means that no run has begun yet. - Start
prevasnull, meaning no text so far. - Loop over the positions from 0 while
i < lines.Count. For a list the size isCount, notLength. - Test whether the line continues the run:
count > 0 && lines[i] == prev. Both parts matter. The first part says that a run exists, and the second says that this line matches it. - If so, add 1 to
count. - Otherwise a different line has arrived, so the previous run is over. Check whether its
countequals 1. On the very first linecountis 0, so nothing is added. - Add
prevtoresultwhen that check is true: this run stood alone. - Start the next run: set
prevtolines[i], - and set
countto 1. - After the loop, test
count == 1again. This handles the final run, which no later line closed. - Add
prevtoresultif it passed. - Return
string.Join("\n", result). The separator goes between two lines only, so there is no newline after the last one.
The solution in C#
class Solution {
public string UniqOnce(List<string> lines) {
List<string> result = new List<string>();
int count = 0;
string prev = null;
for (int i = 0; i < lines.Count; i++) {
if (count > 0 && lines[i] == prev) {
count++;
} else {
if (count == 1) {
result.Add(prev);
}
prev = lines[i];
count = 1;
}
}
if (count == 1) {
result.Add(prev);
}
return string.Join("\n", result);
}
}
The C# details worth knowing:
==compares string contents.stringis a reference type, but it overloads==to compare the characters, solines[i] == previs true for two separate string objects holding the same text.nullis a valid string.prevstarts asnull, and thecount > 0test states plainly that the first line always starts a run, instead of relying on a comparison withnull.List<T>versus arrays.resultis a list because we don't know how many lines survive. An array has a fixed length from the moment it is created.string.Joinon an empty list returns the empty string"", so an empty input or an input where every line repeats needs no special case.
Complexity
Time: O(n). The loop visits each line once, and each visit does a constant amount of work apart from comparing two strings, which costs time proportional to their length. string.Join makes one more pass over the result.
Space: O(n). In the worst case, no line repeats, so result holds all of them. Besides the list, the method uses two variables.
Edge cases and common mistakes
- Empty list. The loop never runs,
countstays 0, and the result is"". - Single line.
["x"]becomes one run of length 1, which only the check after the loop adds. Without that check the answer would be wrongly empty. - Everything repeats.
["a", "a"]gives"". - Non-adjacent duplicates.
["a", "b", "a"]gives"a\nb\na". Using a counter dictionary over the whole list would drop bothas, which is not what this command does. - Empty lines. An empty string is an ordinary line.
["", "", "x", ""]gives"x\n": the two empty lines at the start repeat and are dropped,xstays, and the final empty line is alone, so it stays too and leaves a trailing newline. - Forgetting to flush the last run. The loop only closes a run when a different line comes along.
- Adding
lines[i]instead ofprev. When the run ends,lines[i]is the line that started the next run.
Testing
["a", "a", "b", "c", "c", "c"]gives"b".[]gives"".["x"]gives"x".["a", "b", "a"]gives"a\nb\na".["a", "a"]gives"".
