Find the Missing Number



You are given a list of n-1 integers and these integers are in the range of 1 to n. There are no duplicates in list. One of the integers is missing in the list. Write an efficient code to find the missing integer.
package com.kartik.missing.element;

public class FindTheMissingElement {

 public static void main(String[] args) {
  int[] provideData = { 5, 6, 7, 8, 10, 11, 12, 13 };
  FindTheMissingElement missingElement = new FindTheMissingElement();
  System.out.println(missingElement
    .findMissingElementOfSequenceArray(provideData));
 }

 private int findMissingElementOfSequenceArray(int[] data) {
  int startElement = data[0];
  int endElement = data[data.length - 1];
  int result = 0;
  for (int i = startElement; i <= endElement; i++) {
   result = result ^ startElement;// XOR operation
  }
  for (int i = 0; i <= data.length - 1; i++) {
   result = result ^ data[i];// XOR operation
  }
  return result;
 }

}

OutPut: 9

How to Algo work?







Previous
Next Post »