import java.util.HashMap; /** * MatchPairedColors */ public class MatchPairedColors { public static void main(String[] args) { int[] ar = { 1, 1, 1, 1, 3, 2, 2, 3, 4 }; System.out.println(numberOfPairedSocks(ar)); } private static int numberOfPairedSocks(int[] arr) { int numofP = 0; HashMap socksCount = new HashMap<>(); for (int sock : arr) { if (socksCount.containsKey(sock)) { socksCount.put(sock, socksCount.get(sock) + 1); } else { socksCount.put(sock, 1); } } for (int count : socksCount.values()) { numofP += count / 2; } return numofP; } }