sachinrahulsourav - 2 months ago 14x

Java Question

I was asked this question in an interview today. I have tried a solution but would like to know if there's a better way to solve this:

**Question**: I have an arraylist say of 500,000 elements such that the value of each element of the arraylist is same as the index. For ex: list.get(0) = 0; list.get(1) = 1 ...etc. But only one element is out of sync with this ordering [i.e list.get(i) != i]. How do you find that element.

**My Answer**: Iterate over the list using multiple threads each thread handling a certain splice of the arraylist each time comparing list.get(i) with i. When the element is found, set some boolean variable to indicate to other threads that the element has been found.

Is there a way to solve this problem without iterating over the list? Or a better way?

Answer

In the worst case you have to examine each element, so you can't improve on the `O(n)`

time complexity.

With this in mind, the best algorithm is to scan the array list from start to finish. This way you're making best use of the available memory bandwidth.

It is not entirely clear to me how or why threading has entered the picture. It seems out of place. Was it part of the question?

Source (Stackoverflow)

Comments