Given an unsorted array of positive integers, find the length of the longest subarray whose elements when sorted are continuous. Can you think of an O(n) solution?
Examp
Don't get your hopes up, this is only a partial answer.
I'm quite confident that the problem is not solvable in O(n)
. Unfortunately, I can't prove it.
If there is a way to solve it in less than O(n^2)
, I'd suspect that the solution is based on the following strategy:
O(n)
(or maybe O(n log n)
) whether there exists a continuous subarray as you describe it with at least i
elements. Lets call this predicate E(i)
.i
for which E(i)
holds.The total running time of this algorithm would then be O(n log n)
(or O(n log^2 n)
).
This is the only way I could come up with to reduce the problem to another problem that at least has the potential of being simpler than the original formulation. However, I couldn't find a way to compute E(i)
in less than O(n^2)
, so I may be completely off...