Given an integer array P[1..n], we want to build an array S[1..n]:
Among the members in P[1..i-1] that are larger than P[i], we choose P[k] with the largest index (1<=k< i <=n). S[i] will hold the value of P[k]. If there are no numbers greater than P[i] in P[1..i-1] we place 0 in S[i].
Obviously, the first element in S[] will be 0, as there are no elements before it. The others can be found using iteration through the array P[], however, that will take O(n^2)
, as it is the sum of the series 1+2+...+n=[1/2n(n+1)]
.
Is there a way to do this in linear time? I have thought about using stacks, as it will help with pulling the highest index with a larger value, however, any way I try to implement it still requires me to go through the created stack, so it is actually worse - time to create the stack, and time to pop out until reaching the desired element, all over again and again. Perhaps there's another way?
Any ideas/suggestions/hints on how it could be done?
Examples:
P[5,4,9,7,8]-->S[0,5,0,9,9]
P[1,5,2,3]-->S[0,0,5,5]
Clarification:
We should assign to S[i] the highest indexed number, still greater than P[i] in P[1..i-1]. For example, assume P[8,2,1]. While 8 is the greatest value, S[3] will hold the value 2, as it is the highest indexed number still greater than P[3]. -->S[0,8,2].
Edit:
I believe I have an O(n) solution, using a stack. the idea in pseudocode:
BuildS(P[])
Temp-StackNIL
for(i<--1 up to n)
while(Temp-Stack≠NIL)
if(P[i]<=top[Temp-Stack])
pop(Temp-Stack) //goes back to while
else
S[i]<--top[Temp-Stack]
push(Temp-Stack,P[i]) //goes back to for
S[i]<--0 //out of while
push(Temp-Stack,P[i]) //goes back to for
Am I having it right?