i was going through an interview question ..and came up with logic that requires to find:
Find an index
j
for an elementa[j]
larger thana[i]
(withj < i
), such that(i-j)
is the largest. And I want to find thisj
for every indexi
in the array, inO(n)
orO(n log n)
time withO(n)
extra space.`
What I have done until now :
1) O(n^2)
by using simple for loop
s
2) Build balanced B.S.T. as we scan the elements from left to right and for i
'th element find index of element greater than it. But I realized that it can easily be O(n)
for single element, therefore O(n^2)
for entire array.
I want to know if it is possible to do it in O(n)
or O(n log n)
. If yes, please give some hints.
EDIT : i think i am unable to explain my question . let me explain it clearly:
i want arr[j]
on left of arr[i]
such that (i-j)
is the largest possible ,and arr[j]>arr[i]
and find this for all index i i.e.for(i=0 to n-1).
EDIT 2 :example - {2,3,1,6,0}
for 2 , ans=-1
for 3 , ans=-1
for 1 , ans=2
(i-j)==(2-0)
for 6 , ans=-1
for 0 , ans=4
(i-j)==(4-0)