Last active
June 8, 2018 16:59
-
-
Save leosabbir/6f1bc4798a56fed80580c58c19f82c22 to your computer and use it in GitHub Desktop.
Finds the two missing numbers in the given array which contains numbers from 1 to n inclusive except two numbers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* File: MissingTwoNumbers.java | |
* Created: 6/6/2018 | |
* Author: Sabbir Manandhar | |
* | |
* Copyright (c) 2018 WorldLingo Inc. | |
*/ | |
/** | |
* @author Sabbir Manandhar (lastname)(dot)(firstname)(at)gmail(dot)com | |
* @version 1.0 | |
*/ | |
public class MissingTwoNumbers { | |
public static void main(String[] args) { | |
int[] input = new int[]{10, 9, 5, 6, 8, 3, 7, 4, 11, 1, 2, 13, 15}; | |
int[] res = find(input); | |
System.out.println(res[0] + " " + res[1]); | |
} // main | |
//------------------------------------------------------------------------------- | |
/** | |
* Finds the two missing numbers in the array | |
* @param input input array containing numbers [1,n] except two numbers | |
* @return array of two missing numbers | |
*/ | |
public static int[] find(int[] input) { | |
long sum = findSumOfMissingNumbers(input); // find sum of missing numbers | |
int pivot = (int) sum / 2; | |
// Compute the missing number in lower half | |
int lowerHalfXOR = 0; | |
for (int i = 1; i <= pivot; i++) { | |
lowerHalfXOR ^= i; | |
} | |
for (int i = 0; i < input.length; i++) { | |
if (input[i] <= pivot) { | |
lowerHalfXOR ^= input[i]; | |
} | |
} | |
// Compute the missing number in upper half | |
int upperHalfXOR = 0; | |
for (int i = pivot + 1; i <= input.length + 2; i++) { | |
upperHalfXOR ^= i; | |
} | |
for (int i = 0; i < input.length; i++) { | |
if (input[i] > pivot) { | |
upperHalfXOR ^= input[i]; | |
} | |
} | |
return new int[]{lowerHalfXOR, upperHalfXOR}; | |
} // find | |
//------------------------------------------------------------------------------- | |
/** | |
* Finds the sum of the two missing numbers in the input array | |
* @param input array containing numbers [1,n] except two numbers | |
* @return sum of the two missing numbers | |
*/ | |
public static long findSumOfMissingNumbers(int[] input) { | |
int n = input.length + 2; | |
int expectedSum = (n * (n+1)) / 2; | |
int actualSum = 0; | |
for (int num : input) { | |
actualSum += num; | |
} | |
return expectedSum - actualSum; | |
} // findSumOfMissingNumbers | |
//------------------------------------------------------------------------------- | |
} // MissingTwoNumbers |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment