• + 0 comments

    C# Solution

        public static int sockMerchant(int n, List<int> ar)
        {
            Dictionary<int, int> pairs = new Dictionary<int, int>();
            
            for (int i = 0; i < n; i++) {
                if (pairs.ContainsKey(ar[i])) pairs[ar[i]]++;
                else pairs[ar[i]] = 1;
            }
            
            int sum = 0;
            foreach (KeyValuePair<int, int> pair in pairs) {
                sum += pair.Value / 2;
            }
            
            return sum;
        }
    

    Grouping up each socks and then just divide each group by 2. In C#, when a mathematical operation would result in a floating-point number for integer, the decimal would be concatenated. So if Sock 1 has 5 socks, divided by 2 it would result in 2 pairs - which is correct. Probably could optimize the loop further but the idea was there.