Amazon Interview Question for Software Engineer / Developers


Country: United States
Interview Type: Phone Interview




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

- Create a hashmap of <element, count> pairs from the first array.
- Iterate through the second array and find matching elements.
- If the count of the matching element is greater than 0, print the element and
decrease the count in the map by 1.

static void commonElements(int[] arr1, int[] arr2){
        HashMap<Integer, Integer> countMap = new HashMap<Integer, Integer>();
        for(int e : arr1){
            if(countMap.containsKey(e)){
                int count = countMap.get(e);
                countMap.put(e, count + 1);
                
            }else{
                countMap.put(e , 1);
            }
            
        }
        
        for(int e : arr2){
            if(countMap.containsKey(e)){
                int count = countMap.get(e);
                if(count > 0){
                    System.out.println(e);
                    countMap.put(e , count - 1);
                }
            }
            
        }
        
    }

- learner December 27, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

Good answer. Couple of improvements:
1) Find the smaller array and make countMap for it.
2) In the second loop, when count == 0, it's probably better to remove the key from the map.

- Just an Intern December 27, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Good suggestions!

- learner December 27, 2012 | Flag
Comment hidden because of low score. Click to expand.
3
of 3 vote

I think probably the hash is one option here.

1> I will hash the elements of one array into the hash table.
2> For Every element in the second array try to find the collision and for each collision print value.
Time Complexity = O(m)
Space Complexity = Hash Table Creation.

- hprem991 December 27, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

it will not handle duplicates as given in the question

- Anonymous December 27, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Why not? Maintain the number of duplicates in the value field. So, while scanning the first array, when second 2 is encountered, updated the hash record as <key=2; value=2>. Now, when iterating the second array, when the first 2 is encountered decrement the value to <key=2; value=1> and in this way duplicates can easily be maintained!

- BoredCoder December 27, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Just remove the element when detected as duplicate in array

- Just remove the element when detected as duplicate in array December 27, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Create a bit set and while iterating through array1, set the bit corresponding to the value at that index. Now traverse array2 and if the bit for the current index in array2 is set, then display this value.

- Anonymous December 27, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

what about repeated elements in the array

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

I've found a nice answer for this question:

import java.util.*;
public class CountTest {     
    public static void main(String... args) {        
        Integer[] array1 = {9, 4, 6, 2, 10, 10};
        Integer[] array2 = {14, 3, 6, 9, 10, 15, 17, 9};                    
        Set hashSet = new HashSet(Arrays.asList(array1)); 
        Set commonElements = new HashSet();        
        for (int i = 0; i < array2.length; i++) {
            if (hashSet.contains(array2[i])) {
                commonElements.add(array2[i]);
            }
        }
        System.out.println("Common elements " + commonElements);
    }    
}

- Tarik December 27, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Your solution is using O(n) additional space, but if we don't have space constrains I think I would use this solution.

- Kamy December 27, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

how is this code handling duplicates

- viz December 27, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

It puts all the elements from Array1 into a hashtable(lets say) . for each element in Array2 check in O(1)time if it is also in Array1.

- Kamy December 27, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

I think it would give error in handling duplicates..For instance
S1={2}
s2={2,2,2}
Now the output should be only 2...but your code will give 222...Please correct me if I am wrong

- Anuj Agrawal January 18, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

My approach.

1>Use inbuilt sort routine and sort both arrays.
2>iterate both arrays with two different pointers.
3>compare values and if equal in both array append to new blank array
4>if not equal advance pointer of array with smaller value.

total O(m+n)

- tks December 27, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Even if you use inbuilt sort routine is still sorting.. so that means you are using O(n log n+ m log m) time to sort both arrays. Then you iterate through both, but in the end you still have : Time Complexity : O(nlogn + mlogm)

- Kamy December 27, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

The hashing approach is faster but requires O(n) memory, while this sorting approach is slower but requires O(1) memory. And this is the kind of question interviewer likes because if you answer one version they can impose some constraints and make you come up with the other as well.

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

1) FInd the length of the each arrays
2) Sort the Biggest size array
3) take the first element of the non-sorted array do binary search on the sorted array continue till last element of non-sorted array.

then complexity will be size of non sorted array * log(Size of sorted array)

- Balaswamy December 27, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Sorting of your bigger array will take nlogn... Are you considering that?

- Messiah December 27, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Not just that! In cases, when either of the arrays have duplicate elements, i dont think this solution would work. Cuz, even if array1 has only one occurrence of say, 2. It'll return 'true' for any number of 2's from array2.

- madCode December 29, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

1) FInd the length of the each arrays
2) Sort the Biggest size array
3) take the first element of the non-sorted array do binary search on the sorted array continue till last element of non-sorted array.

then complexity will be size of non sorted array * log(Size of sorted array) + sorting of bigger array

- Balaswamy December 27, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Use a third array temp:

1.Put all the elements of arr1 into temp such that 5 goes to temp[5] ...
2.Iterate over arr2 and for every value check if temp[value]==null to find duplicates

- suvrokroy December 27, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

@ learner this is the exact solution expected...

- Minnu December 27, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Sort both array then find out common elements!!

- MI December 27, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<stdio.h>

int hashtable[10];
int hashcount[10];

int hashval (int key)
{
    return key;
}

void buildhash (int *a, int size)
{
    int i,hash;

    for (i = 0; i < size; i++)
    {
        hash = hashval(a[i]);
        hashcount[hash]++;
        hashtable[hash] = a[i];
    }
}

int main() {
    int i,hash;
    int a[] = {5,6,4,2,2};
    int b[] = {4,2,2,1,6,5,5,3};

    buildhash(a,sizeof(a)/sizeof(int));

    for (i = 0; i<(sizeof(b)/sizeof(int)); i++) {
        hash = hashval(b[i]);
        if (hashtable[hash] && hashcount[hash]) {
            printf("%d ",b[i]);
            hashcount[hash]--;
        }
    }
    printf("\n");
    return 0;
}

- teja December 28, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

@teja : Thank you teja

- Minnu December 28, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I Think a better solution could be as below ( Except its not printing repetitive common elements )

import java.util.HashSet;
import java.util.Set;


public class ArrayIntersection {
static int[] arr1 = {5,6,4,2,2};
static int[] arr2={4,2,2,1};
public static void main(String[] args) {
Set<Integer> setA = new HashSet<Integer>();
Set<Integer> setB = new HashSet<Integer>();
for(Integer iFirstArray : arr1){
setA.add(iFirstArray);
}
for(Integer isecondtArray : arr2){
setB.add(isecondtArray);
}

Set<Integer> common = new HashSet<Integer>(setA);
common.retainAll(setB);
System.out.println(common);
}

}

- Gaurav Kapoor December 29, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

for i in b:
	if i in a:
		andlist+=(i,)

- mailming December 30, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

1. Create a map of array 1 ( Key = Number, Value = 0)
2. Iterate through array 2 ( Increment value by 1 if match)

Time Complexity O(M+N)
Space Complexity O(M)

#include <iostream>
#include <map>
using namespace std;

void common(int arr1[], int arr2[], map<int, int> &data, int size1, int size2)
{
	// Arr1 = M, Arr2 = N

	// Insert Data
	// Insert O(M), Space O(M)
	for(int i=0; i<size1; i++)
	{
		pair<int, int> p(arr1[i], 0);

		if ( data.count(arr1[i]) == 0)
			data.insert(p);
		// Igonore Duplicate
	}
	
	// Search
	for(int i=0; i<size2; i++)
	{
		if ( data.count(arr2[i]) > 0)
			data.at(arr2[i]) += 1;
	}

}

int main()
{
	
	int arr1[] = {5,6,4,2,2};
	int arr2[] = {4,2,2,1};

	map<int, int> m;

	common(arr1, arr2, m, sizeof(arr1)/sizeof(arr1[0]), sizeof(arr2)/sizeof(arr2[0]));

	return 0;
}

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

I am using bit map to find the intersected values. But the range is limited
for integer (0-65535).

Complexity O(m+n)

#include <stdio.h>

int main() {
int arr1[] = {5,6,4,2,2};
int arr2[] = {4,2,2,10,15,12};
int hash = 0;
for (int i=0;i<5;i++) {
hash = hash | (1<<arr1[i]);
}


for (int j=0;j<6;j++) {
int hash1 = hash;
if (((hash1 >> arr2[j]) & 1) == 1) {
printf("\nIntersected value %d",arr2[j]);
}
}
}

- Sivaram February 11, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

1. Create a structure:
struct hash{
int element;
int count;
}
2. Create a hash table of above structure.
3. Traverse first array and store in hash table and increment count value if value is still present in hash table.
3. Traverse second array and decrements value of count in hash table till it is greater than 0. And print value of second array.

- Amit March 03, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

Hi Please find my approach :

public static void main(String args[]){
int[] arr1 = {5,6,4,2,2};
int[]arr2 = {4,2,2,1};

for(int i=0;i<arr1.length-1;i++){

for(int j=0;j<arr1.length-1;j++){

if(arr1[i]==arr2[j]){
System.out.print(arr1[i]);
}
}
}
}

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

Sorry got to downvote for several reasons:
(1) It's O(n^2), slower than O(n) with Hashtable and O(nlogn) with sorting
(2) The inner-for loop is iterating till "arr1.length-1" instead of "arr2.length-1"
(3) Perhaps most importantly, if arr1 = {5, 6, 4, 2} then you will still print 2 twice

- Sunny January 02, 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