tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Articles > Java > Coding Examples > Missing number in a Sequence of Numbers

Missing number in a Sequence of Numbers 

In a sequence of first N natural numbers one number is missing. Find the missing number ?

File Name  :  
com/bethecoder/tutorials/coding/examples/MissingNumberTest.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.coding.examples;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * In a sequence of first N natural numbers one number is missing. Find the number ?
 */
public class MissingNumberTest {

  /**
   @param args
   */
  public static void main(String[] args) {
    int totalNum = 10;
    
    Integer [] nums = 1234678910};
    System.out.println("Missing number in " 
        Arrays.asList(nums" is " + getMissingNumber(nums, totalNum));
    
    System.out.println("Missing number in " 
        Arrays.asList(nums" is " + getMissingNumber2(nums, totalNum));
    
    
    nums = new Integer [] { 1234567910};
    System.out.println("Missing number in " 
        Arrays.asList(nums" is " + getMissingNumber(nums, totalNum));
    
    System.out.println("Missing number in " 
        Arrays.asList(nums" is " + getMissingNumber2(nums, totalNum));
    
  }

  /**
   * Gets the missing number in array.
   
   @param nums
   @return
   */
  private static int getMissingNumber(Integer [] nums, int totalNum) {
    List<Integer> mynums = new ArrayList<Integer>(Arrays.asList(nums));
    List<Integer> actualNums = new ArrayList<Integer>();
    
    for (int i = ; i <= totalNum ; i ++) {
      actualNums.add(i);
    }
    
    actualNums.removeAll(mynums);
    
    if (actualNums.size() == 1) { 
      return actualNums.get(0);
    }
    
    return -1;
  }
  
  private static int getMissingNumber2(Integer [] nums, int totalNum) {
    int sum = 0;
    for (int i = ; i < nums.length ; i ++) {
      sum += nums[i];
    }
    
    int actSum = totalNum * (totalNum + 1)/2//sum of n - natural numbers in sequence (n * n+1)/2
    return actSum - sum;
  }
}
   

It gives the following output,
Missing number in [1, 2, 3, 4, 6, 7, 8, 9, 10] is 5
Missing number in [1, 2, 3, 4, 6, 7, 8, 9, 10] is 5

Missing number in [1, 2, 3, 4, 5, 6, 7, 9, 10] is 8
Missing number in [1, 2, 3, 4, 5, 6, 7, 9, 10] is 8



 
  


  
bl  br