Amazon Interview Question for Software Engineer / Developers


Country: United States
Interview Type: In-Person




Comment hidden because of low score. Click to expand.
2
of 6 vote

public void TargetSumMethod(int []numArray, int target)
	{
		HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
		int lookup;
		for(int i=0; i<numArray.length; i++)
			hm.put(numArray[i], i);
		for(int i=0; i<numArray.length; i++)
		{
			lookup = target - numArray[i];
			if((hm.get(numArray[lookup])) != null)
			{
				System.out.println(numArray[i] + "+" + lookup );
			}
				
		}
	}

This should be in O(n)

- RB July 01, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

this will not give the correct results
it will give

original array
1 , 2 , 3 , 4 , 5 ,
output
Pair 5,1
Pair 4,2
Pair 3,3
Pair 2,4
Pair 1,5

i think, we have to remove the items from hasmap , as soon a key is found in hashmap

- ajaypathak July 02, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

I have tried running this
It gives following output
0,5
1,4
2,3
3,2
4,1
5,0

- RB July 03, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

if((hm.get(numArray[lookup])) != null)

change the following to: if((hm.get(lookup)) != null)

Else, Runtime exception occurs if lookup exceeds array size.

- vash July 06, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

The concept is good, and the little workaround can be done to remove same pairs like (3,3) and all. But, what if two 3s are actually present in the array, then we dont want to remove.

So, overall looks wrong.

- anujarora July 10, 2012 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

///
i=0,j=n
while(i<j){
if(a[i]+a[j]>target)
j=j-1
if(a[i]+a[j]<target)
i=i+1
if(a[i]+a[j] == target)
print a[i],a[j]
i = i+1
j=j-1
///

- saurabh July 02, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

hey saurabh this code won't give you the right result.
it will only work if one number is in first half part and other number is in next half part like for this it will work {1,2,3,4,5}
but for this {1,5,3,2,4} it wont try n check it.!!

- paddy July 03, 2012 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class TargetSum {

	public static void main(String[] args) {
		Integer array[] = {1, 2, 3, 4, 5, 1, 3};
		Integer target = 6;

		findPair(array, target);
	}
	public static void findPair(Integer[] array, Integer target) {
		Set<Integer> setArr = new HashSet<Integer> ();
        List<Integer> list = new ArrayList<Integer>();
        list = Arrays.asList(array);
        setArr.addAll(list);
        System.out.println("Pairs are : ");

        for (int i = 0; i < array.length && !setArr.isEmpty();  i++) {
        	System.out.println("i = " + i);
        	Integer temp = array[i];
        	Integer diff = target - temp;
        	setArr.remove(temp);
        	if(setArr.contains(diff)) {
        		System.out.println("(" + temp + ", " + diff + ")");
        		setArr.remove(diff);
        	}
        }
                    
	}
}

- Jay July 07, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

array[] = {1, 2, 3, 4, 5,3};
Ur sol is incorrect . becoz (3,3) should also be in the ans.

- Shobhit July 08, 2012 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

This will print all pairs (based on their indexes), even if we have repeating numbers , e.g.
[1,2,2,3],4
will print (1,3), (2,2).
[1,2,2,2,3],4
will print
(1,3),(2,2),(2,2),(2,2)

import java.util.HashMap;
import java.util.Map;

public class PairSum {
	public void printPairs(int[] arr, int target) {
		Map<Integer, Integer> elementCount = new HashMap<Integer, Integer>();
		for (int el : arr) {
			increaseElementCount(el,elementCount);
		}

		for (int el : arr) {
			Integer count = elementCount.get(target - el);
			if (count != null && count > 0) {
				int matchingPairs = count;
				if (isHalf(el, target)) {
					matchingPairs--;
				}
				for (int i = 0; i < matchingPairs; i++) {
					System.out.println("(" + el + "," + (target - el)+")");
				}
				int numberOfEl = elementCount.get(el);
				elementCount.put(el, --numberOfEl);
			}
		}
	}

	private void increaseElementCount(int el, Map<Integer,Integer> map) {
		Integer count = map.get(el);
		if (count == null) {
			count = 0;
		}
		map.put(el, ++count);
		
	}

	private boolean isHalf(int el, int target) {
		return (target == 2 * el);
	}
	public static void main(String[] args) {
		new PairSum().printPairs(new int[]{0,1,2,2,3,4}, 4);
	}
}

- gadolin July 10, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Either use hashing or sort and den check from start and end

- Luv July 01, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

you could do this using binary search also .

- hubulu July 02, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@hubulu Array is not sorted, when we sort it, then its easy to have one pointer from start and one from end - O(n)

Rather than doing binary search O(nlogn)

- alexander July 02, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

// first sort
static void printPairs(int arr[], int target) {
  Arrays.sort(arr);
  int i = 0;
  int j = arr.length-1;
  while(i<j) {
    int a = arr[i];
    int b = arr[j];
    int sum = a + b;
    if(sum == target) {
      System.out.println("(" + a + ", " + b + ") ");
      i++;
      j--;
    } else if(sum < target) {
      i++;
    } else {
      j--;
    }      
  }
}

// using hashtable
static void printPairs2(int arr[], int target) {
  HashSet<Integer> set = new HashSet<Integer>();
  for(int i : arr) {
    if(set.contains(i))
      System.out.println("(" + (target-i) + ", " + i + ") ");
    else set.add(target-i);
  }
}

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

#include<stdio.h>
#include<conio.h>
void printpairs(int arr[10],int target);
void main()
{
clrscr();
int arr[10],target;
printf("enter elements");
for(int i=0;i<10;i++)
{
scanf("%d",&arr[i]);
}
printf("enter target sum=");
scanf("%d",&target);
printf("pairs are");
printpairs(arr,target);
getch();
}
void printpairs(int brr[],int target)
{
int j,k;
for(k=0;k<10;k++)
{
for(j=k+1;j<10;j++)
{
if(brr[k]+brr[j]==target)
printf(" %d %d\n",brr[k],brr[j]);
}
}
}

- ganesh July 01, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

any better optimized answers???

- rajeshp July 01, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Is this array in sorted array?

- rajeshp July 01, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

it won't matter, if array is sorted or not

- RB July 01, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

If the array is sorted you can use two pointers from either ends, if its not sorted then can use hashing but will increase the space complexity

- abc July 02, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

findPair(int a[],int sum)
{
i=0;
j=n-1;

while( i<= j)
{
temp = a[i]+a[j];
if( sum == temp)
print(a[i],a[j])
else if( temp < sum)
i++
else
j--
}
}

- Arulmozhi July 02, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

since the question is not clear about if the array is sorted here are the solutions with both options:
1.) if the array is not sorted sort it in O(nlogn) and go to step 2 (if needed O(n) time with O(n) space you can use hashset over key = sum - arr[i] and then traverse the array and search if the value is in the hashset)
2.) if the array is sorted set two pointers in both ends and move the low++ or high-- depending on the sum requested. This is O(n)

here is Java implementation

public void printPair(int[] arr, int sum) {
  int low = 0;
  int high = arr.length - 1;
  
  while (low < high) {
   if (arr[low] + arr[high] == sum)
    System.out.format(“(%s, %s) ”, arr[low++], arr[high]);
   else if (arr[low] + arr[high] < sum)
    low++;
   else
    high--;
  }
 }

- GKalchev July 02, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Initialize a temp list.
for every int in a[]
if(sum - a[i]) is present in list, print a[i] and sum - a[i]
else add a[i] to the list

- siva July 03, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I didn't compile... Just rough thought...

array.Sort(); // Sort array at first if permitted

int left = 0;
int right = array.Length - 1;

while (left <= right)
{
if (array[right] > target)
{
right--;
continue;
}

while (array[left] + array[right] <= target)
{
right--;
}

if (array[left] + array[right] == target)
{
push(left, right);
}

left++;
}

- TS July 03, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void findTargetSum(int[] pairsArr,int targetSum)
{
Map arrHashMap=makeHash(pairsArr);
int val;
for(int i=0;i<pairsArr.length;i++)
{
val=targetSum-pairsArr[i];
if(arrHashMap.containsKey((val)))
{
if(Boolean.valueOf(arrHashMap.get(val).toString())==true){
System.out.println(" valid answer:" +pairsArr[i]+","+(targetSum-pairsArr[i]));
}
}
arrHashMap.put(pairsArr[i],false);

}
}
public static Map makeHash(int[] pairsArr)
{
Map arrHashMap=new HashMap(pairsArr.length);
for(int i=0;i<pairsArr.length;i++)
arrHashMap.put(pairsArr[i],true);
return arrHashMap;
}

Doesn't handle the special case inputs EX 2,3,4,5,6,7,8 and target sum:10 displays 5,5

- buddyram July 04, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Following check will work for special case

void pritnSum2(int a[], int sum) {
		Map<Integer, Integer> hm = new HashMap<Integer,Integer>();
		for(int i =0; i < a.length ; i++) 
			hm.put(a[i], i);
		for(int i =0; i < a.length; i++) {
			int key = sum - a[i];
				if(hm.get(key) != null && a[i] != key) {
					System.out.println("(" + key + "," + a[i] + ")");
				}
			
		}
	}
}

- Naga July 06, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

O(n):

void printPairs(int a[], int target){
			
		//start from left and right side of the array
		int left=0;
		int right=a.length-1;
		
		int toggle = 1;
		
		//continue until you meet
		while(left!=right){
			//if sum equals target print
			if(a[left]+a[right]==target){
				System.out.println("i=" + left+ "; j=" + right);
				left++;
				right--;
			} else {
				//use the toggle to move by one position
				//once for left, once for right, in turns
				if(toggle == 1){
					left++;
				} else {
					right--;
				}
				//switch the toggle
				toggle = 1 - toggle;
			}
		}
	}

- radek1st July 04, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

ignore me, it doesn't work for other inputs

- radek1st July 04, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

you need to play with the value of toggle,
what I am seeing here is u r just decreasing the value of toggle, when ever controls comes into else block

- ajaypathak July 04, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

now it works :)

void printPairs(int a[], int target){
			

		//start from left and right side of the array
		int left=0;
		int right=a.length-1;

		//ignore the elements greater or equal than the target
		for(int x=0; x<a.length; x++){
			if(a[x]>=target){
				right = x-1;
				break;
			}
		}

		while(left<right){

			if(a[left]+a[right]==target){
				System.out.println("a[" + left+ "] = " + a[left] + "; a[" + right + "] = " + a[right] + "; sum = " + (a[left]+a[right]));
				left++;
				right--;
			} else {
				
				if(Math.abs((target/2)-left) < Math.abs((target/2)-right)){
					left++;
				} else {
					right--;
				}
			}
		}
	}

- radek1st July 04, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

static void findPair(final int a[], final int sum)
	{
		for (int i = 0; i < a.length; i++)
		{
			for (int j = i + 1; j < a.length; j++)
			{
				b++;
				if (sum == a[i] + a[j])
				{
					System.out.println(a[i] + "--" + a[j]);
				}
			}
		}
	}

- Aravindtri July 05, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

static void findPair(final int a[], final int sum)
	{
		for (int i = 0; i < a.length; i++)
		{
			for (int j = i + 1; j < a.length; j++)
			{
				if (sum == a[i] + a[j])
				{
					System.out.println(a[i] + "--" + a[j]);
				}
			}
		}
	}

- aravindtri July 05, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here is what i would do

1. Sort the list[i] 1<=i<=n
2. Make a differencelist[i] = targetsum-list[i] 1<=i<=n
3.Do a binary search of each item in differencelist[i] on the list. If a match is found i.e differcelist[i]=list[k] where 1<=k<=n then you have a pair to make the target sum which is (list[i], list[k])

Complexity:
Sort - Best at O(nlogn)
Creating Difference list = O(n)
BInary Search for 1 element = logn
Binary search for n element = O(nlogn.)
Total complexity is O(nlogn)

Space Complexity-
O(2n)=>O(n)..

- Anonymous July 07, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void TargetSum(int[] array, int target)
    {

      Dictionary<int, int> hashMap = new Dictionary<int, int>();

      int lookup = 0;     
     
      for (int i = 0; i < array.Length; i++)
      {
        lookup = target - array[i];

        if (hashMap.ContainsKey(lookup) == true)
        {
          Console.WriteLine("Pair {0},{1}", lookup, array[i]);

        }
        else
        {
          hashMap.Add(array[i], array[i]);
        }
      }



    }

- ajaypathak July 07, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

@Ajay why we need a dictionary?. Cant it be a simple list that you can lookup for that number?

- Anonymous July 08, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

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

void printPairs(int *a , int n ,int target){
int head = 0;
int tail = n - 1;
while ( head != tail ) {
if (a[head] >= target) break;
if ( a[head] + a[tail] == target )
{
cout << a[head] << " + " << a[tail] << " = " << target << endl;
head = head + 1;

}
else if (a[head] + a[tail] > target) tail = tail - 1;
else if (a[head] + a[tail] < target) head = head + 1;
}
}

int main() {

int A[10] = {10,12,1,5,3,4,7,6,2,8};
int n = sizeof(A) / sizeof(int);
sort(A, A + n);
int target = 11;
printPairs(A , n, target);
return 0;
}

- alan July 11, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

How is this logic?

for i = 1 to 5
	for j = 1 to 5
		if i = j
		 continue
		else
		 if (a[i] + a[j] = target)
		   for k 1 to 5
		    if a[i] = c[k] and a[j] = b[k]
		     exist
		    else
		     doesnt exist
		    end if
		   end for
		   if doesnot exist
		   	move a[i] to b[n]
		   	move a[j] to c[n]
		   end if
		 end if
		end if
	end for
end for
print pair:
for i = 1 to 5
 print "(b(i),c(i))"
end for

- Gauri July 11, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

a correction, we will increment the value of n after moving values in b[n] and c[n]

- Gauri July 11, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

#import<stdio.h>
#import<stdlib.h>
#import<string.h>
void findPairs(int *array,size_t len, int sum)
{
        int lookUp;
        int *a = (int*)malloc(sizeof(array));
        a = (int *)memcpy(a, array, sizeof(int)*len);
        for(int i = 0; i < len; i++)
        {
                if(a[i] == -1000)
                        continue;
                lookUp = sum - a[i];
                int j = 0;
                while(j < len)
                {
                        if(a[j] == lookUp)
                        {
                                printf("(%d, %d)", a[i], a[j]);
                                a[j] = -1000;
                                break;
                        }
                        j++;
                }
        }
}

int main()
{
        int a[] = {1, 2, 4, 3, 5};
        int target = 6;
        findPairs(a, (sizeof(a)/sizeof(int)), target);
}

- Anonymous July 15, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

A working Python Code

def getPairForSumN(item_list, N):
    hash_map = {}
    set_pair = set([])
    count = 0
    for item in item_list:
        hash_map[item] = N-item
    for k,v in hash_map.items():
        if hash_map.get(k,None) is not None and hash_map.get(hash_map.get(k, None) ) is not None:
            half_count = 0
            if N%2 == 0 and k == N/2:
                for each in item_list:
                    if each == k:
                        half_count += 1
                        if half_count >=2:
                            set_pair.add((k,v))
            else:
                set_pair.add((k,v))
            hash_map.pop(k)
                
            count += 1
    return set_pair

- invincibleveer July 16, 2012 | 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