Skip to content

Instantly share code, notes, and snippets.

@ardovic
Created June 22, 2019 17:24
Show Gist options
  • Select an option

  • Save ardovic/e77dac8ac6a127d87388006538ef769b to your computer and use it in GitHub Desktop.

Select an option

Save ardovic/e77dac8ac6a127d87388006538ef769b to your computer and use it in GitHub Desktop.
Sample solution to an algorithmic problem (Find two missing numbers in an array)
class FindTwoMissingNumbersInArray {
public static void main(String args[]) {
int[] arrInput = new int[]{7, 0, 1, 2, 5, 3, 4, 6};
System.out.println("For input array: " + Arrays.toString(arrInput));
int maxVal = arrInput.length + 1;
int sumMiss = getReqSum(maxVal) - getRealSum(arrInput, maxVal);
int avgMiss = sumMiss / 2;
int missSmall = getReqSum(avgMiss) - getRealSum(arrInput, avgMiss);
System.out.println("Missing numbers are: " + missSmall + " and " + (sumMiss - missSmall));
}
static int getReqSum(int n) {
return n * (n / 2) + (n % 2 == 0 ? n / 2 : n);
}
static int getRealSum(int[] arr, int maxVal) {
int sum = 0;
for (int i : arr) {
if (i <= maxVal)
sum += i;
}
return sum;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment