How do we find duplicates number in int array repeated more than two times. One of the example I have is as below
public static void main()
{
int[] array = { 3, 7, 9 , 7, 4, 9, 7 , 9}
Dictionary<int,int> dic = new Dictionary<int,int>();
foreach(var Val in array)
{
if(dict.containskey(Val)
dic[Val] ++;
else
dic[Val] = 1 ;
}
foreach (var pair in dic)
if(key.value > 2 )
Console.WriteLine(pair.key)
}
Is there any better way to do this? I was been asked in one of the interview. I gave above solution which was been rejected.
Edit :: I was been asked to write a program which takes less memory and good in performance.. It should not use linq or any inbuilt C# extension method...
Group your items and take only those with more than 2 occurrences:
array.GroupBy(x=>x).Where(x=>x.Count()>2).Select(x=>x.Key)
Since there aren't any constraints provided to the elements that can be contained in this array, you should have asked the interviewer whether he wants a solution with O(n) time complexity and O(n) space complexity** or a solution with O(nlogn) time complexity and O(1) space complexity**.
Without constraints to the elements in the array there's no solution in O(n) time complexity and O(1) space complexity**.
And because he rejected your solution (which is O(n) time complexity and O(n) space complexity**) apparently he was seeking for the second. One way to achieve that is to first sort the array and then iterate over it to find the duplicates.
Remark**: the example values provided for space complexity do not include the space occupied by the original array, only the extra space needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With