DEV Community

Python Tutorial
Python Tutorial

Posted on

Find the Missing Number in a Given Permutation Using Java

Image description

Introduction

Finding the missing number in a given permutation is a common problem in programming, frequently encountered in coding interviews, competitive programming, and real-world applications. A permutation of N elements consists of numbers from 1 to N+1, but one number is missing. Our goal is to efficiently identify the missing element using Java.

In this Java tutorial, we will explore multiple approaches to solving this problem, including brute force, mathematical methods, and bitwise techniques. By the end of this tutorial, you will be equipped with multiple strategies to solve similar problems efficiently.


Understanding the Problem Statement

A permutation is an ordered sequence of distinct integers from 1 to N+1, where one element is missing. Given an array A of length N, our task is to find the missing number.

Example 1

Input:

A = [2, 3, 1, 5]
Enter fullscreen mode Exit fullscreen mode

Output:

4
Enter fullscreen mode Exit fullscreen mode

Explanation:

The numbers in the full permutation should be [1, 2, 3, 4, 5]. The number 4 is missing.


Approach 1: Brute Force Solution (O(N²) Complexity)

A simple way to find the missing number is by checking each number from 1 to N+1 and verifying if it is present in the array.

Java Implementation

public class MissingElement {
    public static int findMissingNumber(int[] A, int N) {
        for (int i = 1; i <= N + 1; i++) {
            boolean found = false;
            for (int num : A) {
                if (num == i) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                return i;
            }
        }
        return -1; // Should never reach here
    }

    public static void main(String[] args) {
        int[] A = {2, 3, 1, 5};
        int N = A.length;
        System.out.println("Missing Number: " + findMissingNumber(A, N));
    }
}
Enter fullscreen mode Exit fullscreen mode

Time Complexity:

  • Checking each number (1 to N+1) requires O(N) operations.
  • Iterating through the array in each iteration makes it O(N²) in the worst case.
  • Not efficient for large inputs.

Approach 2: Using Sum Formula (O(N) Complexity)

A more efficient way is using the sum formula for the first N natural numbers:

[
\text{Sum} = \frac{(N+1) \times (N+2)}{2}
]

Then, subtract the sum of the elements in the given array from this sum to find the missing number.

Java Implementation

public class MissingElementSum {
    public static int findMissingNumber(int[] A, int N) {
        int expectedSum = (N + 1) * (N + 2) / 2;
        int actualSum = 0;

        for (int num : A) {
            actualSum += num;
        }

        return expectedSum - actualSum;
    }

    public static void main(String[] args) {
        int[] A = {2, 3, 1, 5};
        int N = A.length;
        System.out.println("Missing Number: " + findMissingNumber(A, N));
    }
}
Enter fullscreen mode Exit fullscreen mode

Time Complexity:

  • Calculating sum takes O(N) time.
  • Only one loop, making it efficient for large arrays.
  • Best choice for numerical-based problems.

Approach 3: Using XOR Property (O(N) Complexity, O(1) Space)

The XOR property can help find the missing number. The XOR of two identical numbers is 0, and XOR of any number with 0 remains unchanged.

[
\text{XOR}(1 \oplus 2 \oplus ... \oplus N+1) \oplus (\text{XOR of array elements}) = \text{Missing Number}
]

Java Implementation

public class MissingElementXOR {
    public static int findMissingNumber(int[] A, int N) {
        int xorFull = 0;
        int xorArray = 0;

        // XOR of numbers from 1 to N+1
        for (int i = 1; i <= N + 1; i++) {
            xorFull ^= i;
        }

        // XOR of all elements in the array
        for (int num : A) {
            xorArray ^= num;
        }

        return xorFull ^ xorArray;
    }

    public static void main(String[] args) {
        int[] A = {2, 3, 1, 5};
        int N = A.length;
        System.out.println("Missing Number: " + findMissingNumber(A, N));
    }
}
Enter fullscreen mode Exit fullscreen mode

Time Complexity:

  • Each XOR operation runs in O(1) time.
  • Total complexity is O(N), making it highly efficient.
  • Uses O(1) space, making it memory-efficient.

Comparison of Approaches

Approach Time Complexity Space Complexity Efficiency
Brute Force (Nested Loops) O(N²) O(1) Slow
Sum Formula Method O(N) O(1) Fast
XOR Approach O(N) O(1) Very Fast

Best Choice:

  • Sum Formula is recommended for most scenarios.
  • XOR Method is best when dealing with bitwise operations or low memory constraints.

Example Walkthrough

Input:

A = [2, 3, 1, 5]
Enter fullscreen mode Exit fullscreen mode

Using Sum Formula:

  • Expected sum: (5 × 6) / 2 = 15
  • Actual sum: (2 + 3 + 1 + 5) = 11
  • Missing number = 15 - 11 = 4

Using XOR Method:

[
(1 \oplus 2 \oplus 3 \oplus 4 \oplus 5) \oplus (2 \oplus 3 \oplus 1 \oplus 5) = 4
]

Output:

Missing Number: 4
Enter fullscreen mode Exit fullscreen mode

Conclusion

The Java Program to Find the Missing Element in a permutation is a fundamental problem in programming. We explored multiple solutions, from brute force to optimized approaches using mathematical formulas and XOR operations.

This Java tutorial provided a step-by-step guide, helping you understand different strategies to solve similar problems efficiently.

Mastering these techniques will prepare you for real-world scenarios and coding interviews. 🚀

Happy coding! 🎯

Image of Quadratic

AI spreadsheet assistant for easy data analysis

Chat with your data and get insights in seconds with the all-in-one spreadsheet that connects to your data, supports code natively, and has built-in AI.

Try Quadratic free

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay