Find all duplicate values in Array containing random number which are repeating or distinct.
Example: 3, 4, 8, 6, 7, 9, 4,3, 77 Ans = {4, 3}
Example: 3, 8, 6, 7, 9, 4, 77 Ans = {}
Solution:
We loop through the array one element at a time and we throw it in to a hashtable if we didn't do this before. But if we already add it to the hashtable , then we found the answer and we add it to our result array or list.
public IList<int> solution(int[] A) {
IList<int> ans = new List<int>();
Hashtable ht = new Hashtable();
for(int i=0; i< A.Length; i++) {
if (!ht.ContainsKey(A[i]))
ht[A[i]] = A[i];
else {
ans.Add(A[i]);
}
}
return ans;
}