Amazon Interview Question for Software Engineer / Developers


Country: India
Interview Type: Phone Interview




Comment hidden because of low score. Click to expand.
7
of 9 vote

I think the fastest way would be to traverse the array and foreach positive number(ignore negatives) you mark it in an auxiliar array, and then you traverse the auxiliar array, and the first index you find in 0 would be the number your looking for. Complexity time O(n), memory O(n)

in case you don't want to use any extra memory: just order the array and traverse until you find the first positive number, then continue traversing until you find a positive number that is not consecutive to the previous one, for example, array:{1,2,3,5}, you will find the 1 but the 2 is consecutive, so you have to continue to traverse until you finde the 5 that is not consecutive to 3, and the answer would be the previous(3) +1 (4).
the complexity for this is O(nlog(n)) and the memory O(1)

the code for the first algorithm:

foreach(x in array)
           if(x>0)
                  axu[x]=1;
    for(inti i=1;i<length(aux);i++)
              if(aux[i]==0)
                     return i;

and the second algorithm:

sort(array); //merge, quick nlog(n)
      for(int i=0;i<length(array);i++)
              if(array[i]>0 && array[i-1]>=0 && array[i]-array[i-1]>1)
                       return array[i-1]+1;

- Franky January 03, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

For the first solution, do you mean the auxiliary array can be of the size at most length of given array? I think that much should be sufficient. And look up the first missing. Ignore 0th element.

- Anonymous January 03, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

just one small bug for second solution, for sorted array -1 3 4 5,
the missing min positive int is 1. so you have to add an if before your code: if(array[i]>0 && array[i-1]<=0 && array[i]!=1) return 1;

- zyfo2 January 04, 2013 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

so what i get from above is:
- first traverse the array, get number of positive elem = N.
- have an aux array of size = N,
- traverse the original array, mark all the positive numbers, which are less than N
- traverse aux array, return first unmarked position

- Old Monk January 04, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Hi nice solution. Can u plz help me in understanding this q in more better way. m jst confuse abt edge cases. wot will be ans if 1. all zero. 2. all negetive. 3. all continous- 1,2,3,4,5 like this.

thanks

- sameer.careercup January 06, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Hi, the brother upstairs, I can help you resolve these cases:first, if all zero, return 1 as the missing minimum positive; second if all the numbers are negative, also return 1 as the missing minimum positive, third, if all the numbers are like this, in my opinion this topic will missing its raw intent and I think you have no need to consider this case.

- yingsun1228 January 15, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@Franky ... the space require will be O(N) where N is the largest number in the array.

So if the array have large numbers (1,-2 , 20000, 5, 4000,0, -3,8000000) then the amount of space which will be wasted in creating the auxiliary array will be huge as in this case the auxiliary array would comsume 8000000*int_size space when there are only few +ve numbers so it might not be a good idea to create the auxiliary array

- vik January 17, 2013 | Flag
Comment hidden because of low score. Click to expand.
4
of 4 vote

Insert only positive values into a min heap (n). for i = 1 to empty heap, check the top of the heap for i else return i. Each remove is (logn) so worts case is nlogn best case is n.

- lodown414 January 03, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

can not agree with u more

- oohtj January 06, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Insert into min heap is logn.
So to insert n elements, it is nlogn

Even best case is nlogn

- Anonymous January 07, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

step 1 : Construct a binary tree bottom up... root will minimum of 2 children. If both are negative return min of 2 negative , if one is negative, make positive number the root

step 2 : At the end of step 1 root will be the minimum positive element. Now find 2nd positive minimum.

step3 : Start from the root and find minimum among elements that competed with root. This will return second positive minimum.

step 4 : if second is next to first repeat step 3 until u find a positive elem that is not immediately the next

step 5 : return the the prev minimum + 1

complexity O( nlogn). At each iteration u need to store the 2 nodes that are under consideration

- Ihateme January 03, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

A O(n) method is expected.

- Praveen January 03, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

1. sort: O(NlgN) time + O(1) space
2.counting sort: O(N) time+O(N) space

- Anonymous January 03, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 2 vote

what do you mean by missing number?

- Jackie January 03, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

The smallest positive value not in the array, like for {1, 2, 4} it's 3 for {2, 5, 8} it's 1

- H January 04, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.io.*;
import java.util.*;

public class Answer {
        public static void main (String args[]) {
                FindMinPositive solution = new FindMinPositive();
                solution.getAnswer(args);
        }
}

class FindMinPositive {
        Set<Integer> InputSet = new TreeSet<Integer> ();
        public void getAnswer(String args[]) {
                ArrayList<Integer> intList = new ArrayList<Integer> ();
                for (String item: args) {
                        intList.add(Integer.parseInt(item));
                }
                System.out.println("input: " + intList);
                InputSet.addAll(intList);
                System.out.println("set: " + InputSet);
                think();
        }
        private void think() {
                int min=1;
                for (int item: InputSet) {
                        if (item > 0 && item >= (min+1)) {
                                System.out.println(min+1);
                                break;
                        }
                }
        }
}

- lims1 January 03, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Sorry for mistakes:

import java.io.*;
import java.util.*;

public class Answer {
        public static void main (String args[]) {
                FindMinPositive solution = new FindMinPositive();
                solution.getAnswer(args);
        }
}

class FindMinPositive {
        Set<Integer> InputSet = new TreeSet<Integer> ();
        public void getAnswer(String args[]) {
                ArrayList<Integer> intList = new ArrayList<Integer> ();
                for (String item: args) {
                        intList.add(Integer.parseInt(item));
                }
                System.out.println("input: " + intList);
                InputSet.addAll(intList);
                System.out.println("set: " + InputSet);
                think();
        }
        private void think() {
                int min=1;
                for (int item: InputSet) {
                        if (item > 0 && item > (min+1)) {
                                System.out.println(min+1);
                                break;
                        }
                        else if(item > 0) min = item;
                }
        }
}

- lims1 January 03, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static int findTheSmallestMissingInteger(int[] array)
	{
		int smallest = Integer.MAX_VALUE, smallest2 = Integer.MAX_VALUE;

		for(int i = 0; i< array.length; i++)
		{
			if(array[i] > 0 && array[i] < smallest2)
			{
				if(array[i] < smallest){
					smallest2 = smallest;
					smallest = array[i];
					}
				else
				smallest2 = array[i];
			}	
		}
		if(smallest == 1 && smallest+1 != smallest2)
			return smallest+1;
		 return	smallest2-1;	

	}

complexity is O(n)

- rashid January 03, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

I also think the same way .I i not getting other solution of construting auxaliary array or BSt r HEAP.

- Raj January 04, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

findTheSmallestMissingInteger ... if I am right, this function finds the smallest 2 elements and returns the missing number based on these 2 numbers. it will not work if consecutive numbers are present... e.g and array has negative numbers and 1,2,3,4 ... for this array your code will not return the answer which is 5 ... your code will find 1 and 2 as the smallest 2 numbers and will return 2-1 = 1

Raj ... by auxiliary array, it means you declare another array ... you only have to declare the auxiliary array to be of the same size as the original array . then fill it with zeros... and use hashing(enter 1 in the index corresponding to the value of the positive integer in the original array) to enter all the positive integers into this auxiliary array ... any positive integer that is outside the limit of the size of the auxiliary array need not be entered into the array ... then traverse that array and findout the missing integer ... the first positive index that has a 0 will be the missing integer ...

there is an edge case that there is no missing integer which means an error should be returned or return the (maximum positive integer + 1) depending on what the interviewer needs

just take an example and you will get it ... this method requires extra space .... if sorting is used, it will take more time but will not need extra space ... I dont know about the heap and the binary tree versions of the solution ...

Let me know in case you have any queries

- Anand January 04, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

//Thanks Anand.
I want to clean up my mess so here is my solution.

	public static int findTheSmallestMissingInteger(int[] array)
	{
		Map<Integer, Boolean> cache = new HashMap<Integer, Boolean>();
		for(int i = 0; i < array.length; i++)
		{
			if(array[i] > 0)
			{
				cache.put(array[i], true);
			}
		}
		int i = 1;
		while(i <= cache.size()){
			if(cache.get(i) == null)
				return i;
			i++;
		}
		
		return i+1;
	}

- rashid January 04, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Anand, I am having trouble understanding how you can use the values of the first array as the index into the aux.

Consider an array of numbers such as {90000, 90001, 90003}. You will allocate an aux array of size 3 and then try to index into this array using 90000... clearly not the result we are hoping for.

Am I missing something here?

- Tom S January 04, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

thanks anand got it..

- Raj January 04, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

static int findNextMin(int[] iArr)
        {
            Hashtable positives = new Hashtable();
            
            foreach (int i in iArr)
            {
                if (i > 0)
                    positives.Add(i, i);
            }

            int num=1;

            while (positives.Contains(num))
                num++;
                               
            return num;
        }

- derek January 04, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 2 vote

Let N be the length of the array.

The minimum positive number that is missing must be <= N+1.

This gives us an O(N) time and O(N) bitspace algorithm.

Create a bit-vector of 1,2,..N, and mark the bits corresponding to the numbers present in the array which are <=N+1. Pick the first unmarked bit.

If we are allowed to modify the array, we can make it O(1) space.

The highest voted solution space usage is not O(N) (but idea is similar). it is O(MAX) where MAX is the highest element in the array.

- Loler January 04, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Rightly pointed.

- Fayaz January 06, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

O(n) time, o(n) space using hashmaps:
1. iterate through each element & store each element in a hashmap (keep the largest element)
2. iterate 1 through the largest element
for each iteration, check if that element is in the hash map ... if not -> this is the largest missing value
if you go through the entire loop, the largest missing value is largest element + 1

- H January 04, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

nice approach....Though it is not very practical if you have the max positive value very large....it is similar to doing bucket sort and traversing the sorted array.

- Anuj Agrawal February 02, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote
First Sort the given array and then check for minimum positive missing number by traversing the sorted array Time Complexity: O(nlogn), Space Complexity : O(1) {{{ // First sort the array //Traverse to fine minimum positive missing number public int findMinimum(int arr[]){ int minimum = 0; boolean minFound = false; for(int i=0; i<(arr.length - 1); i++){ //if next element in array is positive and not consecutive if((arr[i] >= 0) && (arr[i+1] != (arr[i]+1))){ minFound = true; minimum = arr[i]+1; break; } } if(!minFound){ //if all elements in array are -ve if(arr[arr.length - 1] < 0) minimum = 0; else //if all are positive consecutive numbers minimum = arr[arr.length-1] + 1; } return minimum; } Please comment if its not correct or missing anything. - SA January 05, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

is this even a valid question

- coding ninja January 07, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Apart from the above solutions we can approach in the following manner too.

1. Find the minimum positive integer, if not 1, return 1.
2. Else take it as pivot, using quick sort method, place it to its position.
3. Take any +ve number from the right of 1 and again quick sort method place it in its position. Suppose the number is x. Pos[x] - Pos[1] == x-1, then repeat the same process to sub array that is to the right side of x else to the left side of x and greater than 1.

- Ashish Anand January 08, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

scan the array, keep the smallest two positive integers.

- TT January 10, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

If the array starts from 2,eg {2, 5, 3, -4, 6}, will the answer be 1? Then in that case below solution can work.

int num = 1;
    for (int j = 0; j < n; j++) {
         if (a[j] == num)
              num++;
    }
    return num;

Please let me know if I have thought of something wrong.

- anantkaushik89 January 16, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

It is a very elegant idea, but if the array is not sorted, like this one:a[] = {9, 20, -2, 3, -45, 23, 5, 2,1}, you will get the wrong number. So, you should sort the given array first, then your idea will work better.

- yingsun1228 January 17, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Idea is good you can make it more optimized by adding one if condition

Arrays.sort(array);
		int min = 1;
		int num = 1;
		boolean found = false;
		for (int j = 0; j < array.length; j++) {
			if (array[j] == num) {
				num++;
				found = true;
			} else {
				if (found) {
					break;
				}
			}
		}
		return num;

- Giridhar January 19, 2013 | Flag
Comment hidden because of low score. Click to expand.
-1
of 1 vote

Here is O(n) solution.

#include <iostream>
using namespace std;
int findSmallestMissNum(int ar[],int size);
int main()
{
    int input[] = {9,20,-2,-45,23,5,1};
    cout<<findSmallestMissNum(input,7);
    getchar();
    return 0;
}
int findSmallestMissNum(int ar[],int size)
{
    int small1, small2;
    small1 = INT_MAX;
    small2 = INT_MAX;
    
    for( int i = 0 ; i < size ; i++)
    {
         if( ar[i] >= 0 && ar[i] < INT_MAX )
         {
             small2 = small1;
             small1 = ar[i];
         }
    }
    if( small1 < small2)
        return small1 + 1;
    else
        return small2 + 1;
}

- Ravi January 04, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

sorry for mistake..

if( ar[i] >= 0 && ar[i] < INT_MAX )

should be

if( ar[i] >= 0 && ar[i] < small1 )

- Ravi January 04, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

What if you have this array { 1,2,3,4,5}

you only keep two small numbers, so you sould keep 1 and 2, but the answer is 6

- Anonymous January 04, 2013 | Flag


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More