Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here's a relatively simple solution that's <code>O(N lg(N))</code> that doesn't rely on the entries being among finitely many integers (in particular, it should work for any ordered data type).</p> <p>We assume the output is to be stored in two arrays; <code>lowleft[i]</code> will at the end contain the number of distinct values <code>x[j]</code> with <code>j &lt; i</code> and <code>x[j] &lt; x[i]</code>, and <code>highright[i]</code> will at the end contain the number of distinct values <code>x[j]</code> with <code>j &gt; i</code> and <code>x[j] &gt; x[i]</code>.</p> <p>Create a balanced tree data structure that maintains in each node, the number of nodes in the subtree rooted at that node. This is fairly standard, but not a part of the Java standard library I think; it's probably easiest to do an AVL tree or so. The type of the values in the nodes should be the type of the values in your array.</p> <p>Now first iterate <em>forward</em> through the array. We start with an empty balanced tree. For every value <code>x[i]</code> we encounter, we enter it into the balanced tree (near the end there are <code>O(N)</code> entries in this tree, so this step takes <code>O(lg(N))</code> time). When searching for the position to enter <code>x[i]</code>, we keep track of the number of values less than <code>x[i]</code> by adding up the sizes of all left subtrees whenever we take the right subtree, and adding what will be the size of the left subtree of <code>x[i]</code>. We enter this number into <code>lowleft[i]</code>.</p> <p>If the value <code>x[i]</code> is already in the tree, we just carry on with the next iteration of this loop. If the value <code>x[i]</code> is not in there, we enter it and rebalance the tree, taking care to update the subtree sizes correctly.</p> <p>Each iteration of this loop takes <code>O(lg(N))</code> steps, for a total of <code>O(N lg(N))</code>. We now start with an empty tree and do the same thing iterating <em>backward</em> through the array, finding the position for every <code>x[i]</code> in the tree, and every time recording the size of all subtrees to the right of the new node as <code>highright[i]</code>. Total complexity therefore <code>O(N lg(N))</code>.</p>
    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.
    2. VO
      singulars
      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