Repeat & Missing Number
Hashmap approachimport java.util.*; public class RepeatAndMissingNumber { public static int[] findRepeatAndMissing(int[] arr) { int n = arr.length; Map<Integer, Integer> map = new HashMap<>(); int[] result = new int[2]; // result[0] = repeated, result[1] = missing // Count occurrences manually using containsKey() for (int num : arr) { if (map.containsKey(num)) { map.put(num, map.get(num) + 1); // Increment count if already present } else { map.put(num, 1); // Insert with count 1 if not present } } // Identify repeated and missing numbers for (int i = 1; i <= n; i++) { if (map.containsKey(i)) { if (map.get(i) > 1) { result[0] = i; // Repeated number } } else { result[1] = i; // Missing number } } return result; } public static void main(String[] args) { int[] arr = {3, 1, 2, 5, 3}; // Example: 3 is repeated, 4 is missing int[] ans = findRepeatAndMissing(arr); System.out.println("Repeated: " + ans[0] + ", Missing: " + ans[1]); } }
Leave a Comment