Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>As @j_random_hacker pointed out, this is quite similar to <a href="https://stackoverflow.com/q/5739024/134633"><em>Finding duplicates in O(n) time and O(1) space</em></a>, and an adaptation of my answer there works here too.</p> <p>Assuming that the "bag" is represented by a 1-based array <code>A[]</code> of size <code>N - k</code>, we can solve Qk in <code>O(N)</code> time and <code>O(k)</code> additional space.</p> <p>First, we extend our array <code>A[]</code> by <code>k</code> elements, so that it is now of size <code>N</code>. This is the <code>O(k)</code> additional space. We then run the following pseudo-code algorithm:</p> <pre><code>for i := n - k + 1 to n A[i] := A[1] end for for i := 1 to n - k while A[A[i]] != A[i] swap(A[i], A[A[i]]) end while end for for i := 1 to n if A[i] != i then print i end if end for </code></pre> <p>The first loop initialises the <code>k</code> extra entries to the same as the first entry in the array (this is just a convenient value that we know is already present in the array - after this step, any entries that were missing in the initial array of size <code>N-k</code> are still missing in the extended array).</p> <p>The second loop permutes the extended array so that if element <code>x</code> is present at least once, then one of those entries will be at position <code>A[x]</code>.</p> <p>Note that although it has a nested loop, it still runs in <code>O(N)</code> time - a swap only occurs if there is an <code>i</code> such that <code>A[i] != i</code>, and each swap sets at least one element such that <code>A[i] == i</code>, where that wasn't true before. This means that the total number of swaps (and thus the total number of executions of the <code>while</code> loop body) is at most <code>N-1</code>.</p> <p>The third loop prints those indexes of the array <code>i</code> that are not occupied by the value <code>i</code> - this means that <code>i</code> must have been missing.</p>
    singulars
    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.
    3. 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