Given an array , for every element I need to find the smallest element to the right of the given element which is greater than the current element.
Mathematically,
For every index i
in array A
, I need to find index j
such that
A[j] > A[i]
j > i
A[j] - A[i] is minimum
I need to find j
for every index i
The brute force solution would be O(n^2)
and I am hoping to do better. I am thinking that an O(n log n)
solution is possible using self-balancing BST but that seems pretty complex. Moreover I need a O(n)
solution.
Is there a O(n)
solution to this problem? Is there a proof that the lower bound is O(n log n)
?