Puzzle : finding out repeated element in an Array -


size of array n.all elements in array distinct in range of [0 , n-1] except 2 elements.find out repeated element without using temporary array constant time complexity.

i tried o(n) this.

   a[]={1,0,0,2,3};     b[]={-1,-1,-1,-1,-1};     i=0;     int required;     while(i<n)     {       b[a[i]]++;       if(b[a[i]==1)         required=a[i];     }     print required; 

if there no constraint on range of numbers i.e allowing out of range also.is possible o(n) solution without temporary array.

  1. look first , last number
  2. calculate sum(1) of array elements without duplicate (like know sum of 1...5 = 1+2+3+4+5 = 15. call sum(1)). aaronmcsmooth pointed out, formula sum(1, n) = (n+1)n/2.
  3. calculate sum(2) of elements in array given you.
  4. subtract sum(2) - sum(1). whoa! result duplicate number (like if given array 1, 2, 3, 4, 5, 3, sum(2) 18. 18 - 15 = 3. 3 duplicate).

good luck coding!


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -