Problem overview
The method uniq takes a List<String> of lines and drops adjacent duplicates: in every run of identical consecutive lines only the first is kept. The surviving lines are returned as one string, joined by newline characters. This is a small version of the Unix uniq command.
For lines = ["a", "a", "b", "c", "c", "c", "a"] the result is "a\nb\nc\na". Printed, that is:
a
b
c
a
The last "a" survives because it is not next to the first run of "a"s. Only consecutive duplicates are removed, so this is not the same as removing every repeated value.
Approach: compare with the last line kept
A line is a duplicate when it equals the line right before it. Since the lines of a run are all equal, comparing with the last line that was kept gives the same answer as comparing with the previous input line. The method builds a result list, and for each line asks one question: is the result empty, or does this line differ from the last item in the result? If so, the line starts a new run and is added.
That works without any counters or flags, and the list itself remembers what was kept last. The only special case is the very first line, which has nothing before it. An empty result list covers that case.
Removing all repeated values, not just adjacent ones, would need a set of lines seen so far. This lesson needs no extra structure, because only the neighbour matters.
Step by step
- Create
result, an emptyArrayListheld in aList<String>variable, for the lines to keep. - Loop with an index. A
forloop runsifrom 0 whilei < lines.size().lines.get(i)is the line at positioni. - Decide whether to keep line
i. The condition isresult.isEmpty() || !lines.get(i).equals(result.get(result.size() - 1)). The last item ofresultis at indexresult.size() - 1. The strings are compared withequals, and the!turns "equal" into "differs". The empty check comes first for a reason explained below. - Add the line with
result.add(lines.get(i)). A line equal to the one kept just before it never gets here. - Join and return with
String.join("\n", result). The separator goes only between two lines, so the result has no newline at the end.
The solution in Java
class Solution {
public String uniq(List<String> lines) {
List<String> result = new ArrayList<>();
for (int i = 0; i < lines.size(); i++) {
if (result.isEmpty() || !lines.get(i).equals(result.get(result.size() - 1))) {
result.add(lines.get(i));
}
}
return String.join("\n", result);
}
}
The Java details worth a closer look:
- Short-circuit
||. InA || B, Java evaluatesBonly whenAis false. Whenresultis empty,result.isEmpty()is true, soresult.get(result.size() - 1)never runs. If the two operands were swapped, the first line would callresult.get(-1)and throw anIndexOutOfBoundsException. equalsagainst==. On strings,==compares references, not text. Two lines with the same characters can be different objects, and==would call them different.equalscompares the characters, and it is the right tool here.List.getagainst array indexing. AListhas no[i]; it usesget(i)andsize(). An array would use[i]andlength.- Imports. A standalone file needs
import java.util.*;forListandArrayList.
Complexity
Time: O(n) in the number of lines, times the cost of comparing two lines. Each line is compared with at most one other string, and ArrayList.get and add take constant time on average. Joining copies every kept character once.
Space: O(n). The result list holds up to n references, and the joined string is a new copy of the kept text.
Edge cases and common mistakes
- An empty list. The loop does not run and the result is
"". - One line.
["x"]gives"x": the result is empty at that moment, so the line is kept. - Everything identical.
["z", "z", "z"]gives"z". - Not adjacent.
["a", "b", "a", "b"]gives"a\nb\na\nb". Nothing is removed, because no two neighbours are equal. - Case counts.
["a", "A", "a"]gives"a\nA\na", sinceequalsis case-sensitive. - Empty lines.
["", "", "a"]gives"\na": the two empty lines collapse into one, which comes out as an empty line beforea. - Using
==on strings. It may seem to work for literals typed in the source, but it fails for strings built at run time. - Using a set. A
HashSetwould remove every repeat, and it loses the order of first appearance unless it is aLinkedHashSet. The task keeps repeats that are not adjacent.
Testing
["a", "a", "b", "c", "c", "c", "a"]gives"a\nb\nc\na".[]gives"".["x"]gives"x".["a", "b", "a", "b"]gives"a\nb\na\nb".["", "", "a"]gives"\na".
