fork(2) download
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. public class Test
  5. {
  6. public static void Main()
  7. {
  8. Console.WriteLine("Output {0}", returnSecondDuplicate(new[] { 'x', 'y', 'z', 'x', 'y' }));
  9. Console.WriteLine("Output {0}", returnSecondDuplicate(new[] { 'a', 'a', 'b', 'a', 'c', 'b', 'a', 'c', 'b' }));
  10. Console.WriteLine("Output {0}", returnSecondDuplicate(new[] { 'a', 'a', 'a', 'b', 'a', 'c', 'b', 'a', 'c', 'b' }));
  11. Console.ReadLine();
  12. }
  13.  
  14. public static char returnSecondDuplicate(char[] arr)
  15. {
  16. if (arr.Length == 0)
  17. throw new ArgumentNullException("Empty Array passed");
  18. var dictionary = new Dictionary<char, int>();
  19. var duplicates = new List<char>();
  20. Char second = '\0';
  21. int i = 0;
  22.  
  23. while (duplicates.Count != 2 && dictionary.Count != arr.Length)
  24. {
  25. if (!dictionary.ContainsKey(arr[i]))
  26. dictionary.Add(arr[i], 1);
  27. else if (!duplicates.Contains(arr[i]))
  28. duplicates.Add(arr[i]); // only add duplicates once (ignoring any duplicate duplicates!)
  29.  
  30. second = duplicates.Count == 2 ? arr[i] : second;
  31. i++;
  32. }
  33.  
  34. return second;
  35. }
  36. }
Success #stdin #stdout 0.04s 34000KB
stdin
Standard input is empty
stdout
Output y
Output b
Output b