Missing and Repeating Number in Array with Java Solution

📌 DSA Problem Series – Day 15 | Problem 2 | Array 🔹 Problem: Missing and Repeating Number 🧠 Problem Statement: You are given an array of size N containing numbers from 1 to N. One number is missing One number is repeating Your task is to find both numbers. ✅ Approach Used Use a HashMap to track frequency of elements Identify the repeating number when frequency > 1 Use mathematical sum formula to compute the missing number 💻 Java Solution class Solution { ArrayList<Integer> findTwoElement(int arr[]) { Map<Integer, Integer> map = new HashMap<>(); int n = arr.length; int expectedSum = n * (n + 1) / 2; int repeatingNumber = -1; int actualSum = 0; for (int item : arr) { if (map.containsKey(item)) { repeatingNumber = item; } map.put(item, map.getOrDefault(item, 0) + 1); actualSum += item; } int missingNumber = expectedSum - (actualSum - repeatingNumber); return new ArrayList<>(Arrays.asList(repeatingNumber, missingNumber)); } } ⏱️ Complexity Time Complexity: O(N) Space Complexity: O(N) 🎯 Key Takeaway Combining hashing with basic mathematics makes this problem simple and efficient. This pattern appears frequently in interviews and competitive programming. #DSA #Java #ProblemSolving #Arrays #CodingInterview #LeetCode #HashMap #Backend

  • graphical user interface, text, application

To view or add a comment, sign in

Explore content categories