Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Assuming you meant first next element which is lower than the current element, here are 2 solutions - </p> <ol> <li>Use <code>sqrt(N)</code> segmentation. Divide the array in <code>sqrt(N)</code> segments with each segment's length being <code>sqrt(N)</code>. For each segment calculate its' minimum element using a loop. In this way, you have pre-calculated each segments' minimum element in <code>O(N)</code>. Now, for each element, the next lower element can be in the same segment as that one or in any of the subsequent segments. So, first check all the next elements in the current segment. If all are larger, then loop through all the subsequent segments to find out which has an element lower than current element. If you couldn't find any, result would be <code>-1</code>. Otherwise, check every element of that segment to find out what is the first element lower than current element. Overall, algorithm complexity is <code>O(N*sqrt(N))</code> or <code>O(N^1.5)</code>.</li> </ol> <p>You can achieve <code>O(NlgN)</code> using a segment tree with a similar approach.</p> <ol> <li>Sort the array ascending first (keeping original position of the elements as satellite data). Now, assuming each element of the array is distinct, for each element, we will need to find the lowest original position on the left side of that element. It is a classic RMQ (Range Min Query) problem and can be solved in many ways including a <code>O(N)</code> one. As we need to sort first, overall complexity is <code>O(NlogN)</code>. You can learn more about RMQ <a href="http://community.topcoder.com/tc?module=Static&amp;d1=tutorials&amp;d2=lowestCommonAncestor" rel="nofollow">in a TopCoder tutorial</a>.</li> </ol>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload