## Interview Question

## Interview Answer

10 Answers

Why would you make it so complicated? Why would you compute factorial. If there's a million elements in the array, your algorithm just cried. Algorithm: sweep through the entire array. If the first element is equal to one, print zero. If the first element is equal to two, print one and zero. Now generalize that. There is a special case to consider it it's the last two elements that are missing, which falls into the same category of having an array of size N = 1. It's O(n), which I believe means linear time? And it actually doens't use any additional memory.

The array of integers isn't sorted so your approach doesn't really work fzivkovi.

1. Create a new array of size N, the values of all members are zero. 2. Loop through the input array - Suppose the value of the current member is X - Put 1 to the X-th member of the new array 3. Loop through the new array - If the value of a member is zero, print out the member. It takes O(n) time and O(n) space.

Vee - your answer does not use constant space. It uses linear space.

Since array is from 1...n, we know that all numbers between 1 and N must be represented. so if n = 5, then array should be 1, 2, 3, 4, 5. Therefore: for( i = 0, i < array.length, i++){ if( array[ i ] != i+1){ // this element is missing } }

* This post has been removed. Please see our Community Guidelines or Terms of Service for more information.*

This will be a little confusing since I don't want to write the algorithm for this here. Sort the array in O(N). Start from the first element. If it is not in the right place, set it to 0 and move it to the right place. Do the same to the next element (otherwise you will overwrite it). Do this until your element is in the right place or is equal to 0. Now repeat to all elements in the array. At the end, scan the array and find which elements in the array are equal to 0. This algorithm assumes the array size is N and not N-2, but can be modified to use two variables for the last two elements.

list => [3, 1, 2, 5, 7, 8] prod = reduce(lambda x,y: x*y, [x for x in range(1,9)]) product = reduce (lambda x, y : x * y, list) prod/product => 24 product = prod/product product => 24 sum => 10 100 - 24*4 => 4 x = sum/2.0 + math.sqrt(sum*sum - 4*product)/2.0 x => 6.0 y = sum/2.0 - math.sqrt(sum*sum - 4*product)/2.0 y => 4.0 int(x) => 6 int(y) => 4

// assume array is in A, size to N with two BLANK element. #define BLANK N+1 for(int i =0; i<N; i++) { int x = A[i]; swap(A, x, i); } // A is sorted with blanks in the middle for(int i=0; i< N; i++) { if( A[i] == BLANK) { std::cout << i << std::endl; } }

## Add Answers or Comments

To comment on this, Sign In or Sign Up.

You sweep through the array once and updating 2 variables. The first sums all the numbers in the array. The second multiply them. Now it's just a matter of solving 2 equation with 2 unknowns. x + y = SUM[1..N] - t1 ; x * y = factorial[1..N] / t2.