Build a tiny version of the Unix uniq command. Given a list of lines, drop adjacent duplicate lines (keep only the first occurrence in each consecutive run) and return the surviving lines joined by newline characters (\n).
Function signature:
public String uniq(List<String> lines)
Example:
Input: lines = ["a", "a", "b", "c", "c", "c", "a"] Output: "a\nb\nc\na" When printed: a b c a
Notice that the trailing "a" survives because it is not adjacent to the first run of "a"s — only consecutive duplicates are removed.
Build a
List<String> result and add the current line only if it differs from the last entry in result. Use .equals() for the comparison, NOT ==.
if (result.isEmpty() || !lines.get(i).equals(result.get(result.size() - 1))) {
result.add(lines.get(i));
}
The full solution:
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);
}
}
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
