Given a list of 100 elements, if I take out 1 element from list, How will you find out what is the element removed?
I have been asked this question in one of my interview.
Given a list of 100 elements, if I take out 1 element from list, How will you find out what is the element removed?
I have been asked this question in one of my interview.
Assuming that you are given different references to the contents of the collection before
and after
the deletion of the element, the command
before.removeAll(after);
will leave before
with just one element, i.e. the deleted one, if the remaining elements are not equal to the deleted one.
Otherwise, depending on how the deletion is done, you get the removed element either as a parameter to remove(element)
or as the return value of remove(elementIndex)
, for collections that support indexed deletion (e.g., subclasses of List
).
If you are given the new collection and the old collection then the simplest mechanism is to remove each item in the new from the old. What is left is the difference between the two.
For example, in Java 8:
newCollection.stream().forEach(oldCollection::remove);
This works because the stream
and remove
methods are both in the Collection
interface so it should work for all collections that support remove. Because remove
is called once for each item in newCollection
only a single instance of each will be removed which helps with duplicate items.
If remove
is not supported by the collection then a simple solution is to create a new copy before using this method (e.g. new ArrayList<>(oldCollection)
):
If you are specifically looking for one item in an indexed collection then you can just look for the first one that doesn't match which is much cheaper:
IntStream.range(0, oldCollection.size())
.filter(n -> n >= newCollection.size()
|| !oldCollection.get(n).equals(newCollection.get(n)))
.findFirst();
This returns an Optional
to allow for the situation in which no items have been removed.
Assuming they give you 100 int elements and remove 1 int from the collection. what you can do is to do a sum() for 100 elements and another sum() for the 99 elements. Then you do a subtraction between the two sum and you will get the element that was removed from the collection.