Purpose
I came across this relatively simple question on HackerRank regarding finding missing values across two List
s. I took a fairly straight-forward approach, but is there a "better" / "slicker" way of implementing a solution?
Task
Strategy
- Iterate through
List
with complete data. - If
Integer
is inList
with incomplete data, removeInteger
from bothList
s. Else, addInteger
to aTreeSet
of all missing values.
Implementation
public class MissingNumbersImpl implements MissingNumbers {
@Override
public Set<Integer> identifyMissingNumbers(final List<Integer> all, final List<Integer> incomplete) {
if (all.size() <= incomplete.size()) {
throw new IllegalArgumentException("list containing all numbers must have a size greater than list not containing all numbers");
}
final Set<Integer> missingNumbers = new TreeSet<>();
final Iterator<Integer> iterator = all.iterator();
while (iterator.hasNext()) {
final Integer next = iterator.next();
if (incomplete.contains(next)) {
incomplete.remove(next);
iterator.remove();
} else {
missingNumbers.add(next);
}
}
return missingNumbers;
}
}