Size of an array is n.All elements in the array are distinct in the range of [0 , n-1] except two elements.Find out repeated element without using extra temporary array with con
O(n) without the temp array.
a[]={1,0,0,2,3};
i=0;
int required;
while(i<n)
{
a[a[i] % n] += n;
if(a[a[i] % n] >= 2 * n)
required = a[i] % n;
}
print required;
(Assuming of course that n < MAX_INT - 2n)
This example could be useful for int, char, and string.
char[] ch = { 'A', 'B', 'C', 'D', 'F', 'A', 'B' };
Dictionary<char, int> result = new Dictionary<char, int>();
foreach (char c in ch)
{
if (result.Keys.Contains(c))
{
result[c] = result[c] + 1;
}
else
{
result.Add(c, 1);
}
}
foreach (KeyValuePair<char, int> pair in result)
{
if (pair.Value > 1)
{
Console.WriteLine(pair.Key);
}
}
Console.Read();
Based on @sje's answer. Worst case is 2 passes through the array, no additional storage, non destructive.
O(n) without the temp array.
a[]={1,0,0,2,3};
i=0;
int required;
while (a[a[i] % n] < n)
a[a[i++] % n] += n;
required = a[i] % n;
while (i-->0)
a[a[i]%n]-=n;
print required;
(Assuming of course that n < MAX_INT/2)