Problem overview
This version of the uniq tool behaves like uniq -u. The method uniqOnce receives a List<String> and returns one String: the lines that were not repeated right after themselves, joined by \n. The word that matters is "adjacent". Only a run of identical lines that sit next to each other counts as a repeat.
In the example, ["a", "a", "b", "c", "c", "c"] has three runs: two "a", one "b" and three "c". Only the run of length 1 survives, so the result is "b".
Because only neighbours count, the same text can appear again later without being a repeat. For ["a", "b", "a"] every run has length 1, so the result is "a\nb\na".
Approach: walk the list and measure each run
You don't need to sort or to count how often a line occurs overall. A single pass is enough if you remember two things about the run you are in: its text (prev) and its length so far (count).
- When the current line equals
prev, the run grows: increasecount. - When it differs, the previous run has just ended. If its length was exactly 1, keep it. Then start a new run with the current line and a count of 1.
A run only ends when a different line arrives, and the last run has nothing after it. So the loop never judges the last run, and one more check after the loop has to do that.
Here is the state after each line of the example:
i=0 line=a prev=a count=1 result=[]
i=1 line=a prev=a count=2 result=[]
i=2 line=b prev=b count=1 result=[]
i=3 line=c prev=c count=1 result=[b]
i=4 line=c prev=c count=2 result=[b]
i=5 line=c prev=c count=3 result=[b]
after loop result=[b]
At i=2 the run of "a" ends with a count of 2, so it is dropped. At i=3 the run of "b" ends with a count of 1, so "b" is added. The three "c" lines never reach a count of 1 again, and the check after the loop sees a count of 3 and adds nothing.
Step by step
- Create
result, an emptyArrayListof strings. A list grows as you add lines, which fits an answer whose size you don't know yet. - Create
countat 0. It is the length of the current run, and 0 means no run has started. - Create
prevasnull. It is the text of the current run, empty until the first line. - Loop over the positions of
lineswithifrom 0 tolines.size() - 1. - Test for a continuing run. Two things must both be true: a run exists (
count > 0) and the current line equalsprev. - If so, add 1 to
count. - Otherwise a different line has arrived, so the previous run is over. Check whether its length was exactly 1.
- If it was, add
prevtoresult. A run longer than 1 has a repeat and is dropped. - Start the new run by setting
prevto the current line. - Set
countto 1, because the new run has one line so far. - After the loop, test the last run with the same
count == 1condition. - Add
prevtoresultif that last run stood alone. - Return
String.join("\n", result). The separator goes only between two lines, so the output has no newline at the end.
The solution in Java
class Solution {
public String uniqOnce(List<String> lines) {
List<String> result = new ArrayList<>();
int count = 0;
String prev = null;
for (int i = 0; i < lines.size(); i++) {
if (count > 0 && lines.get(i).equals(prev)) {
count++;
} else {
if (count == 1) {
result.add(prev);
}
prev = lines.get(i);
count = 1;
}
}
if (count == 1) {
result.add(prev);
}
return String.join("\n", result);
}
}
Java details worth knowing:
- Compare strings with
equals.==on twoStringobjects compares references, so two lines with the same text can still be "different".lines.get(i).equals(prev)compares the characters. - The
count > 0guard protects thenull. At the first lineprevisnull. The condition is false beforeequalsis ever called with it, and the first line goes to theelsebranch. There,count == 1is false for a count of 0, so nothing is added by mistake. String.jointakes anyIterableof strings. The first argument goes between the elements. An empty list gives"".- Imports.
ListandArrayListlive injava.util.
Complexity
Time: O(n). The loop visits each line once, and each visit does a constant amount of work apart from the string comparison, which costs at most the length of a line.
Space: O(n). result can hold every line, as in a list where no line repeats next to itself. The two variables prev and count take constant space.
Edge cases and common mistakes
- Forgetting the last run. Without the check after the loop, a lone last line is silently dropped. With the check,
["a"]gives"a". - Empty input. The loop doesn't run,
countis 0, and the result is"". - Keeping one copy of a repeated line. That is plain
uniq. Here a line that repeated back to back disappears entirely:["x", "x", "y", "y"]gives"". - Counting equal lines anywhere in the list. A frequency map would drop
"a"from["a", "b", "a"], but only adjacent repeats count, so the answer is"a\nb\na". - Empty lines are lines. For
["", "", "z"]the two empty strings form a run of 2 and are dropped, so the result is"z". - Comparing with
==. It may seem to work for string literals, then fail for lines built at run time.
Testing
["a", "a", "b", "c", "c", "c"]gives"b".["a", "b", "a", "a"]gives"a\nb".["a", "b", "a"]gives"a\nb\na".["x", "x", "y", "y"]gives"".["", "", "z"]gives"z".[]gives"".
