OneCompiler

Find the duplicate element in an array with O(n) space complexity

153
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace OneCompiler
{
	public class Program
	{
		public static void Main(string[] args)
		{
			int n = int.Parse(Console.ReadLine());
			
			int[] arr = Array.ConvertAll(Console.ReadLine().Split(" "), new Converter<string,int>(StringToInteger));
			
			var duplicates = Duplicates(arr);
			
			for (int i = 0; i < duplicates.Length; i++)
			{
			  Console.WriteLine(duplicates[i] + " ");
			}
		}
		
		private static int StringToInteger(string s)
		{
		  return int.Parse(s);
		}
		
		private static int[] Duplicates(int[] arr)
		{
		  int n = arr.Length;
		  
		  var dictionary = new Dictionary<int, int>();
		  
		  if (n == 0 || n == 1)
		  {
		    return dictionary.Select(x => x.Key).ToArray();
		  }
		  else
		  {
		    for (int i = 0; i < n; i++)
		    {
		      if (dictionary.TryGetValue(arr[i], out var value))
		      {
		        dictionary[arr[i]] += 1;
		      }
		      else
		      {
		        dictionary.Add(arr[i], 1);
		      }
		    }
		    
		    return dictionary.Where(x => x.Value > 1).Select(x => x.Key).ToArray();
		  }
		}
	}
}