Amazon Interview Question for SDE1s


Country: United States
Interview Type: In-Person




Comment hidden because of low score. Click to expand.
8
of 8 vote

Double the index until you find a larger element, then binary search between the last two indices.

- Anonymous February 20, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
2
of 2 vote

If the array is infinite, that means we don't have proper bounds to apply binary search.
So in order to find position of key, first we find bounds and then apply binary search algorithm.

Let low and high be pointing to 1st element of array,
Now compare key with high index element,
->if it is greater than high index element then copy high index in low index and double the high index
->if it is smaller, then apply binary search on high and low indices found.

int find_position(int arr[],int key) // we don't know the size of array
{
    int l=0,h=0,val;
    val=arr[0];
    while(val<k)
    {
        l=h;
        h=2*h;
        val=arr[h];
    }
    // after finding low and high indices, apply binary search between them 
    return binSearch(arr,l,h,k);
}

This would run in O(log n).

- GAURAV February 21, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

CORRECTION :
h should be initialized as 1

- GAURAV February 21, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

I assume k is key :)

- Anon February 25, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

One thing to note is that if arr[h] happens to equal the key while you're finding the bounds, binSearch will be applied to a subarray where the element you want to find is at the very left index. Worst case, it will still be found in O(lgn), but we could also check if a[h] == k during finding the bounds. How valuable this is can be left up to discussion.

- JW March 23, 2015 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

Gallop Search along with linear search. Sounds efficient?

- midha@usc.edu February 20, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Can you please explain further?

- corby February 20, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Log(n) binary search found leftMost and rightMost

- Scott February 20, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

But since it is an infinite array, how do you find the right most?

- MM February 20, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

We can try galloping the values along with linear search. Sounds good?

- Anonymous February 20, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

if the array is infinite and all elements are same what is occurrence of the element?

- Scott February 20, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Double the index until you find a larger element, then binary search between the last two indices.

- ml February 20, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 2 vote

Following is my solution to the above mentioned problem.
Approach: Binary search; count the occurrence when a match is found
Complexity: O(logn)

public int noOfOccurence(int n, int a[])
	{
		int lo=0, hi=a.length-1, m;
		
		while(lo <= hi)
		{
			if((hi - lo) == 1){
				if(a[hi] == n) return 1;
				if(a[lo] == n) return 1;
				else	return -1;
			}
			m = (lo+hi)/2;
			if(a[m] > n){hi = m;}
			else if(a[m] < n){lo = m;}
			else{
				int lt = m , rt = m;
				int count = 0;
				while((lt >= 0) && (rt < a.length)){
					if((a[lt] == n))	count++;
					if((a[rt] == n))	count++;
					else return count-1;
					lt--; rt++;
				}
				return count-1;
			}
		}
		return -1;
	}

- corby February 20, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

if the size of the array is infinity, how you will calculate length?

- noname February 20, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Following is the solution to above mentioned problem.
Approach: Binary search; count the occurrence when match is found
Complexity: O(logn)

public int noOfOccurence(int n, int a[])
	{
		int lo=0, hi=a.length-1, m;
		
		while(lo <= hi)
		{
			if((hi - lo) == 1){
				if(a[hi] == n) return 1;
				if(a[lo] == n) return 1;
				else	return -1;
			}
			m = (lo+hi)/2;
			System.out.println("mid:"+m);
			if(a[m] > n){hi = m;}
			else if(a[m] < n){lo = m;}
			else{
				int lt = m , rt = m;
				int count = 0;
				while((lt >= 0) && (rt < a.length)){
					if((a[lt] == n))	count++;
					if((a[rt] == n))	count++;
					else return count-1;
					lt--; rt++;
					System.out.println("count:"+count);
				}
				return count-1;
			}
		}
		return -1;
	}

- corby February 20, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I have one doubt .
Now it is said that the array is sorted and there may be duplicates,so will it be like this
eg:3,5,6,13,14,14,17,19,29,30,30,50,60
Or is it that the duplicates wont or may be next to each other

- AJ February 20, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Typical CS graduate answers...

The array is sorted, so use it to your advantage. Just index directly to the number you're looking for and then all you need to account for are duplicates that occurred earlier. For example, if you're looking for 151, set your left bound to array[151]. Now you can double your index to find the right bound and do your searching.

- Mr. Experience February 20, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Consider the sample input sequence provided in the post by AJ (i. e. sparse value set), then explain where your algorithm breaks down.

- sk3l February 21, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Consider the input sequence proposed in the post by AJ (i.e. sparse value set). Indexing at the ith position, setting that as the left bound and beginning the subsearch from that point on won't work, as it is not guaranteed that all (or any) instances of the value i will be in the sequence a[i] .... a[2i]....a[4i].... etc.

- sk3l February 21, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

As this is infinite array there won't be end boundary...

- So start searching at exponential index like search at index 2^n where n=0,1,2,3,.....
- Once index is found at index 'i' then

count = 1
 index = i-1;
 while a[i] == a[index] {
	count ++
	index --
 }
 index = i+1;
 while a[i] == a[index] {
	count ++
	index++
 }
 here the value of count would be no. of occurrence of input number

- Anonymous February 20, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

As this is infinite array there won't be end boundary...

- So start searching at exponential index like search at index 2^n where n=0,1,2,3,.....
- Once index is found at index 'i' then

count = 1
 index = i-1;
 while a[i] == a[index] {
	count ++
	index --
 }
 index = i+1;
 while a[i] == a[index] {
	count ++
	index++
 }
 here the value of count would be no. of occurrence of input number

- Anonymous February 20, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Haha, question is wrong, how can you have an array with infinite length, is it Linked list ?

- cleonjoys February 20, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

As per your question it is infinite and sorted, how could anybody sort when the numbers are infinite, what if a number already present comes again => then it should be dynamic and It cannot be static, in either case i would go with hashing techique.

- cleonjoys February 20, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

//use Linear search
public static int countOccurance (int[] array, int key)
{
int count=0;
for (int i=0; i< array.length;i++)
{
if (array[i]==key)
count=count + 1;

}
return count;
}

- Anonymous February 20, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

/**
   * Suppose you have an array with infinite numbers, 
   * which is sorted and there may be duplicates. 
   * Find the occurrence of a number.
   */
  def findDuplicate(xs:Stream[Int], n:Int):Boolean = {
    def helper(previous:Int, index:Int, upperBound:Option[Int]): Boolean = {
      val value = xs(index)
      if(value == n) {
        value == xs(index-1) || value == xs(index+1)
      }
      else if(value < n) {
        val upperValue = upperBound.getOrElse(3*index)
        val nextIndex = index + (upperValue - index)/2
        helper(index, nextIndex, upperBound)
      }
      else {
        val nextIndex = previous + (index - previous)/2
        helper(previous, nextIndex, Some(index))
      }
    }
    helper(0, 1, None)
  }

- diloreto.p February 22, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

The solution instead to iterate on every single element of the list, is doubling the index to check each time, once the value at the index is greater than the value we are looking for, will move to the middle index between the current position and the previous and keep it doing recursively until it converges.

- diloreto.p February 22, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

{{

for ( i=0; i < a.length; i++)
{
if ( a[ i ] == x )
{ count++; }
else if ( count != 0)
{ break; }
}

}}}

- Shiva Charan February 23, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

{

for ( i=0; i < a.length; i++)
{
if ( a[ i ] == x )
{ count++; }
else if ( count != 0)
{ break; }
}

}

- Shiva Charan February 23, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<stdio.h>
#include<string.h>


int main ()

{

    int inf_array[] = {1,2,3,4,5,6,7,8,9,9,12,13,14,15,15,16,17,18,19,20,20};
    int search_num = 20;

    int array_size = sizeof inf_array / sizeof *inf_array;
    int low, high, mid, idx, result;
    low = 0;
    result = -1;
    high = array_size - 1;
    mid = (array_size-1)/2;

    printf("LOW     MID     HIGH    VALUE\n");
    while ( low <= high) {
        printf("%d       %d      %d      %d\n",low, mid, high, inf_array[mid]);
        if ( inf_array[mid] == search_num ) {
            result = mid;
                    // Keep any of the given 3 line based on your requirements.
            high = mid-1;  //first occurance of a number.
            //low = mid+1;   // Last occurance of a number.
            //break;    // just finding.
        } else if ( inf_array[mid] > search_num ) {
            high = mid-1;
        } else {
            low = mid+1;
        }
        mid = (low + high)/2;
    }

    if ( result < 0){
        printf("Number [%d] does not exists in array.\n", search_num);
    } else {
        while ( (inf_array[result] == search_num)  && (result < array_size) ){
            printf("Number [%d] found at index - %d.\n", search_num,result);
            result++;
        }
    }
}

- Sunil Mahato February 25, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

double the index until you find a element larger than the given number and do binary search.
l-lower index;h-higher index, k-key
value=arr[0];
while(value<k)
{
l=h;
h=2*h;
value=arr[h];
}
after finding l and h do binary search

- Vidhushini February 26, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

abc

- Viral February 28, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public int[] product(int[] arr){
        int[] returnArray = new int[arr.length];
        int zeroElementIndex = -1;
        int product = 1;
        
        for(int i=0;i<arr.length;i++){
            if(arr[i] == 0){
                zeroElementIndex = i;
                break;
            }else{
                product = product * arr[i];
            }    
        }

        
        if(zeroElementIndex != -1){
            product =1;
            for(int j=0;j<arr.length;j++){
                if(j != zeroElementIndex)
                {
                    returnArray[j] = 0;
                    product = product * arr[j];   
                }    
            }
            returnArray[zeroElementIndex] = product;
        }else{
            for(int j=0;j<arr.length;j++){
                    returnArray[j] = product/arr[j];
            }
        }
        
        return returnArray;

    }

- Viral February 28, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

/**
This solution runs in O(n).
It traverse through entire array to calculate product. If it finds zero at any element, it will remember that index and breaks the loop.
Now there can be 2 cases:
1) Zero element found at any index: In this case it will set all other index as zero in resulting array and calculate product for zero index element.
2) No element is zero in array: Divide product with individual value of an array to calculate new array elements.
**/

public int[] product(int[] arr){
        int[] returnArray = new int[arr.length];
        int zeroElementIndex = -1;
        int product = 1;
        
        for(int i=0;i<arr.length;i++){
            if(arr[i] == 0){
                zeroElementIndex = i;
                break;
            }else{
                product = product * arr[i];
            }    
        }

        
        if(zeroElementIndex != -1){
            product =1;
            for(int j=0;j<arr.length;j++){
                if(j != zeroElementIndex)
                {
                    returnArray[j] = 0;
                    product = product * arr[j];   
                }    
            }
            returnArray[zeroElementIndex] = product;
        }else{
            for(int j=0;j<arr.length;j++){
                    returnArray[j] = product/arr[j];
            }
        }
        
        return returnArray;

    }

- viralsanghavi7 February 28, 2015 | Flag Reply


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