Data Structures & Algorithms in Java – Binary – Missing Number


Given an array with values between 1 to n , find the missing number between 1 to n that is not present in the array





In the above array of length 9 we have all the numbers from 1 to 9 except 8 , so output is 8

Try out the solution here:



The sum of all numbers upto a given number n can be calculated using the formula:

(n * (n+1)/2)



STEP1: Find the sum of all numbers upto the length of the given array using the formula (n*(n+1)/2) where n is the length of the array

STEP2: Find the sum of all numbers of the given array

STEP3: Find the difference between the sum calculated in step1 and that calculated in step2 , this gives the missing number


class Solution {
    public int missingNumber(int[] nums) {
        int sumGivenNos = 0;
        for(int i=0;i<nums.length;i++){
            sumGivenNos += nums[i];
        return ((nums.length * (nums.length +1))/2) - sumGivenNos;

Time complexity of above code is O(n) and space complexity is O(1)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s