Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <blockquote> <p>You are given an array of n+2 elements. All elements of the array are in range 1 to n. And all elements occur once except two numbers which occur twice</p> </blockquote> <p>Lets modify this slightly, and go with just <code>n</code>, not <code>n+2</code>, and the first part of the problem statement, it becomes</p> <blockquote> <p>You are given an array of n elements. All elements of the array are in range 1 to n</p> </blockquote> <p>So now you know you have an array, the numbers in the array start at 1 and go up by one for every item in the array. So if you have 10 items, the array will contain the numbers 1 to 10. 5 items, you have 1 to 5 and so forth.</p> <p>It follows that the numbers stored in the array can be used to index the array. i.e. you can always say <code>A[A[i]]</code> where i &lt;= size of A. e.g. <code>A={5,3,4,1,2}; print A[A[2]]</code></p> <p>Now, lets add in one duplicate number. The algorithm takes the value of each number in the array, and visits that index. We know if we visit the same index twice, we know we have found a duplicate.<br> How do we know if we visit the same index twice?<br> Yup, we change the sign of the number in each index we visit, if the sign has already changed, we know we've already been here, ergo, this index (not the value stored at the index) is a duplicate number.</p> <p>You could achieve the same result by keeping a second array of booleans, initialised to false. That algroithm becomes</p> <pre><code>A={123412} B={false, false, false, false} for(i = 1; i &lt;= 4; i++) { if(B[A[i]]) // Duplicate else B[A[i]] = true; } </code></pre> <p>However in the MS question you're changing the sign of the element in A instead of setting a boolean value in B.</p> <p>Hope this helps, </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. 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