Find the Repeating and Missing Number

java dev.to

One number in the array appears twice, while another number from the range [1, n] is missing.

Our task is to find both:

  • Repeating Number (A)
  • Missing Number (B)

Example

Input: nums = [1, 2, 2, 4]

Output: [2, 3]
Enter fullscreen mode Exit fullscreen mode

Here, 2 appears twice and 3 is missing.


Brute Force Approach

Intuition

For every number from 1 to n, count how many times it appears in the array.

  • If frequency is 2, it is the repeating number.
  • If frequency is 0, it is the missing number.

Time & Space Complexity

  • Time Complexity: O(N²)
  • Space Complexity: O(1)

Java Code

class Solution {
    public int[] findErrorNums(int[] nums) {

        int repeating = -1;
        int missing = -1;
        int n = nums.length;

        for(int i = 1; i <= n; i++) {

            int count = 0;

            for(int num : nums) {
                if(num == i) count++;
            }

            if(count == 2) repeating = i;
            if(count == 0) missing = i;
        }

        return new int[]{repeating, missing};
    }
}
Enter fullscreen mode Exit fullscreen mode

Better Approach – Hashing

Intuition

Instead of repeatedly counting occurrences, we can maintain a frequency array.

  • Increment frequency for every number.
  • Traverse the frequency array:

    • Frequency 2 → Repeating Number
    • Frequency 0 → Missing Number

This avoids the nested loop and reduces the time complexity to O(N).

Time & Space Complexity

  • Time Complexity: O(N)
  • Space Complexity: O(N)

Java Code

class Solution {
    public int[] findErrorNums(int[] nums) {

        int n = nums.length;
        int[] freq = new int[n + 1];

        for(int num : nums) {
            freq[num]++;
        }

        int repeating = -1;
        int missing = -1;

        for(int i = 1; i <= n; i++) {
            if(freq[i] == 2) repeating = i;
            if(freq[i] == 0) missing = i;
        }

        return new int[]{repeating, missing};
    }
}
Enter fullscreen mode Exit fullscreen mode

How I Remember This Forever

This problem is essentially a combination of two questions:

  1. Find the duplicate number.
  2. Find the missing number.

The easiest observation is that frequencies tell us everything.

Frequency = 2 → Repeating
Frequency = 0 → Missing
Enter fullscreen mode Exit fullscreen mode

Whenever I see:

  • Numbers ranging from 1 to n
  • One duplicate
  • One missing element

My first instinct is to think about frequencies and hashing before moving to mathematical or XOR-based optimizations.


Thanks for reading! 🚀

GitHub: https://github.com/codewithjaspreet
LinkedIn: https://www.linkedin.com/in/jaspreetsodhi482/
Twitter: https://x.com/Jaspree54799902

Source: dev.to

arrow_back Back to Tutorials