Skip to content

Instantly share code, notes, and snippets.

@vigevenoj
Created July 7, 2017 05:07
Show Gist options
  • Save vigevenoj/e5cdbf1aa87ef98ba31b57085e689c9d to your computer and use it in GitHub Desktop.
Save vigevenoj/e5cdbf1aa87ef98ba31b57085e689c9d to your computer and use it in GitHub Desktop.
sample interview question and solution(s) because there's definitely more than one way to solve a problem
import java.io.*;
import java.util.*;
public class Interview {
private static int findMissing(int[] array) {
int length = array.length;
// This three-line implementation is better but possibly less easy to understand.
// We use some math here: sum the numbers from 1 to (length + 1)
// This is what the value would be if there were no missing numbers
// Next, sum the values that *are* present in the array.
// Subtracting the values present from the maximum returns the number that is missing.
// This requires only 1 iteration through the array (to calculate the sum of numbers present)
int OneToN = length * (length+1)/2;
int sum = Arrays.stream(array).sum();
System.out.println("missing " + (OneToN - sum));
// Below is the initial implementation, which requires (n^2)+n comparisons
// make an array of 0..n elements to hold which ones are present
Boolean[] present = new Boolean[array.length+1];
// set them all to false
Arrays.fill(present, false);
// for each position in the array we were passed in,
for (int position = 0; position < length; position ++) {
// determine if array[position] is any of the possible values of 0..n
for (int check = 0; check <= length; check++) {
// if it is,
if (array[position] == check) {
// Mark the value as present and break out of the inner loop (where we check against all values),
// and start checking the next position in the outer loop
present[check] = true;
break;
}
}
}
// There should be one element that is still false in the array of possible values
// because we have set all the other values to true
for (int i = 0; i <= length; i++) {
// If the value is false, return it: it is our missing element
if (!present[i]) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
System.out.println(findMissing(new int[] {5, 0, 1, 2, 4}));
System.out.println(findMissing(new int[] {3, 2, 1}));
System.out.println(findMissing(new int[] {0, 1, 2}));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment