Question

My questions is specific to the problem posed here: Interview puzzle: Jump Game

The top answer claims that it runs in O(n) time. It says that it can do this

because each element need be considered only once (elements that would be considered a second time can be skipped)

However, just checking if we have already considered an element takes a constant time per element, so it ought to take O(n^2), right? O(n) to consider each new element, and O(n) to exclude elements we've already considered. Why is this not the case?

Was it helpful?

Solution

You don't need to check if you have already considered a particular element, you just need to keep track of the index up to which you have already checked, and the highest v (apart from the one you just jumped to) of the array up to that point.

Then you can continue checking from there, comparing each new element to the previous max.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top