How To Solve Missing Number Problem In Java, An Amazon Interview Question
Tags: java, algorithms, programming, beginners
Published: 2022-03-29 06:46:35

## Introduction

We make use of **XOR** principles in finding a missing element.

Let’s see how to achieve this using the **XOR** operator.

## Problem statement

Given an array `nums` containing `n` distinct numbers in the range `[0, n]`, return the only number in the range that is missing from the array.

```javascript
Input: nums = { 9, 6, 4, 2, 3, 5, 7, 0, 1 }

Output: 8

Explanation: n = 9 since there are 9 numbers, so all numbers are in the range [0,9]. 8 is the missing number in the range since it does not appear in nums.
```

Constraints:

1. Do it in Linear Complexity.

2. `n == nums.length`

**Hint:** Use arithmetic progression and go with the Brute force approach. Then optimize it.

## Solution

### Approach 01: Hashtable

This one is better than the one above as we are iterating over all the elements once with `O(n)`extra memory space.

#### Algorithm

This algorithm is almost identical to the Brute force approach, except we first insert each element of `nums` into a `Set`, allowing us to later query for containment in `O(1)` time.

#### Code

```java
import java.util.HashSet;

class MissingNumber {
    private static int helper(int[] nums) {
        HashSet<Integer> set = new HashSet<Integer>();

        for (int num : nums) {
            set.add(num);
        }

        int n = nums.length + 1;

        for (int i = 0; i < n; i++) {
            if (!set.contains(i)) {
                return i;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] nums = {9, 6, 4, 2, 3, 5, 7, 0, 1};
        System.out.println("Missing element in the array is " + helper(nums));
    }
}
```

#### Complexity analysis
**Time complexity:** `O(n)`, the time complexity of for loops is `O(n)` and the time complexity of the hash table operation add is `O(1)`.

**Space complexity:** `O(n)`, the space required by the hash table is equal to the number of elements in `nums`.

### Approach 01: Maths

This uses concepts regarding `n` natural numbers.

#### Algorithm

1. We know the sum of `n` natural numbers is `[n(n+1)/2]`
​
2. Now, the difference between the actual sum of the given array elements and the sum of `n` natural numbers gives us the missing number.

#### Code

```java
class MissingNumber {
    private static int helper(int[] nums) {
        int n = nums.length;
        int expectedSum = ((n * (n + 1)) / 2);

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

        return expectedSum - actualSum;
    }

    public static void main(String[] args) {
        int[] nums = {9, 6, 4, 2, 3, 5, 7, 0, 1};
        System.out.println("Missing element in the array is " + helper(nums));
    }
}
```

#### Complexity Analysis
**Time complexity:** `O(n)`, the time complexity of the for loop is `O(n)`.

**Space complexity:** `O(1)`, as we are not using any extra space.

### Coding exercise

First, take a closer look at these code snippets above and think of a solution.

Your solution must use the `^` operator.

This problem is designed for your practice, so try to solve it on your own first. If you get stuck, you can always refer to the solution provided in the solution section. Good luck!

```java
class Solution{
    public static int missingNumber(int[] nums){
       // Write - Your - Code- Here
        
        return -1; // change this, return missing element; if none, return -1
    }
}
```

The solution is explained below.

> We solved the problem using lookup (Memoization/Hashtable) and using the mathematical formula for the sum of n natural numbers, Let's solve this more efficiently using bit-level operations with `^` or `xor`.

#### Solution review: Bit manipulation

We are dealing with bit manipulation and want to solve all of these problems with Bitwise operators.

#### Concepts

If we take XOR of `0` and a `bit`, it will return that `bit`.

```java
a ^ 0 = a
```

If we take XOR of two same bits, it will return `0`.

```java
a ^ a = 0
```

For `n` numbers, the math below can be applied.

```java
a ^ b ^ a = (a ^ a) ^ b = 0 ^ b = b;
```

For example:

```java
1 ^ 5 ^ 1 = (1 ^ 1) ^ 5 = 0 ^ 5 = 5;
```

So, we can XOR all bits together to find the unique number.

#### Algorithm

1. Initialize a variable, `res = 0`.

2. Iterate over array elements from `0` to `length + 1` and do `^` of each with the above-initialized variable.

Iterate over all the elements and store the value in the variable.

#### Code

Here is the logic for this solution.

```java
class MissingNumber {
    private static int helper(int[] nums) {
        int n = nums.length + 1;
        int res = 0;

        for (int i = 0; i < n; i++) {
            res ^= i;
        }

        for (int value : nums) {
            res ^= value;
        }
        return res;
    }

    public static void main(String[] args) {
        int[] nums = {9, 6, 4, 2, 3, 5, 7, 0, 1};
        System.out.println("Missing element in the array is " + helper(nums));
    }
}
```
#### Complexity analysis

**Time complexity:** `O(n)`, we are using two independent for loops. So Time = `O(n) + O(n)` => `O(n)`. 

Where, `n` is the number of elements in the array, since we need to iterate over all the elements to find a missing number. So, the best and the worst-case time is `O(n)`.

**Space complexity:** `O(1)`, the space complexity is `O(1)`. No extra space is allocated.

## Optimization

Let us optimize the last solution.

We are using two independent for loops to find the missing number.

Now, let’s make it a single for loop. If we have an array of one million integers, then we do two million operations.

We can reduce the number of operations into `n`, where `n` is the array’s size.

Let’s look at the below code.

```java
class MissingNumber {
    private static int helper(int[] nums) {
        int missing = nums.length;

        for (int i = 0; i < nums.length; i++) {
            missing ^= i ^ nums[i];
        }
        return missing;
    }
    
    public static void main(String[] args) {
        int[] nums = {9, 6, 4, 2, 3, 5, 7, 0, 1};
        System.out.println("Missing element in the array is " + helper(nums));
    }
}
```

Here the code has less lines compared to the one above.

## Complexity analysis
**Time complexity:** `O(n)`: Where, `n` is the number of elements in the array, as we need to iterate over all the elements to find a missing number. So, the best, worst-case time is `O(N)`.

**Space complexity:** `O(1)`, the space complexity is O(1), no extra space is allocated.

------

## Learn more

I’ve got a course on bit manipulation that is loved by more than 200k+ programmers. Find it here: [Master Bit Manipulation for Coding Interviews](https://www.educative.io/courses/bit-manipulation?aff=xjzd).

In this course, we learn how to solve problems using bit manipulation, a powerful technique that can be used to optimize our algorithmic and problem-solving skills. The course has simple explanations with sketches, detailed step-by-step drawings, and various ways to solve problems using bitwise operators.