algorithmstack

How to find Find max right using stack?


I was solving the question where we need to find rightSpecialValue for each A[i] in given array A. RightSpecialValue is defined below.

RightSpecialValue: For an index i, it is defined as the index j such that A[j]>A[i] and (j>i). If multiple A[j]'s are present in multiple positions, the RightSpecialValue is the minimum value of j. Here RightSpecialValue is the index j and not A[j].

It could be easily solved using by using stack in O(n) but what if it is changed to "If multiple A[j]'s are present in multiple positions, the RightSpecialValue is the maximum value of j. Here RightSpecialValue is the index j and not A[j]."

is there any better solution than O(n^2)?


Solution

  • is there any better solution than O(n^2)?

    There is at least a O(𝑛log𝑛) solution for it:

    The time complexity of this algorithm is O(log1 + log2 + log3 + ... + log𝑛) = O(𝑛log𝑛).