Amazon Interview Question for Software Engineer / Developers


Country: United States
Interview Type: In-Person




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

1) Sort the array in ascending order in O(n log n).
2) Scan array using two indices one from start and other from end of array
3) Complexity is O(nlogn) + O(n)

public static void findPairs(int[] a, int sum){
		if(a == null || a.length < 2){
			return;
		}
		
		int left = 0;
		int right = a.length - 1;
		java.util.Arrays.sort(a);
		while(left < right){
			int i = a[left];
			int j = a[right];
			if(i+j == sum){
				System.out.println("The pair is "+i+" and "+j);
				left++;
				right--;
			}else if(i+j > sum){
				right--;
			}else{
				left++;
			}
		}

}

- Say March 06, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

An interesting case is if array contains duplicate numbers. Above code will report only one such pair.

e.g. Let the sorted array be 2,5,5,5,6,8,9 and we are searching for elements adding up to 10. This will report only one such pair.

Following Algorithm will help get rid of that issue:
1. Sort
2. For each a[i], Get j = BinarySearch for (x-a[i]) in array between indices i+1 & n-1
3. Print i,j

- fresh_coder March 07, 2012 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

This is similiar to 3sum. We can first sort the array with O(nlogn) complexity, and then use O(nLogn) to find the pairs.

basicalgos.blogspot.com/2012/03/3sum.html

- Andy March 06, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

public class KTestSearch {
private int[] knumber={1,2,3,4,5,6,7,8,9};
	public KTestSearch(int knumber[]) {
		this.knumber=knumber;
	}	
	public void startLogic(int target)
	{
		for(int i=0;i<knumber.length;i++)
		{
			int val=knumber[i];
			if(2*val>=target)
			 break;
			int currentFlag=i;
			int lastFlag=knumber.length;
			findPair(val,target,currentFlag,lastFlag);
		}
	}
	private void findPair(int val,int target,int currentFlag,int lastFlag)
	{
		int mid= (currentFlag+lastFlag)/2;		
		if(val+knumber[mid]>target)
		{			
			findPair(val,target,currentFlag,mid);
		}
		else if(val+knumber[mid]<target&&(lastFlag-mid)>1)
		{		
			findPair(val,target,mid,lastFlag);
		}
		else
			if(target==(val+knumber[mid]))
			System.out.println("The pair of numbers is :: "+val+" + "+knumber[mid]+" == "+target);
	}
	public static void main(String[] args) {
		int[] knumber={1,2,3,4,5,6,7,8,9};	
		KTestSearch ki=new KTestSearch(knumber);
		ki.startLogic(11);

	}
}
complexity :: Sort(nlogn) + Searching (nlog n) = 2nlogn
Output: The list of all possibles 
The pair of numbers is :: 2 + 9 == 11
The pair of numbers is :: 3 + 8 == 11
The pair of numbers is :: 4 + 7 == 11
The pair of numbers is :: 5 + 6 == 11

- Mavugan March 06, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I got the same question.... lol

- CreepyMan March 06, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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

import java.util.List;

public class AdderPair {
public static void main(String[] args) {
int[] inputArr = {1, 2, 3, 45, 50, 55, 56, 76, 98, 99};
List<Map<String, Integer>> output = addPairs(inputArr, 100);
for(Map<String, Integer> eachMap : output) {
System.out.println(eachMap.get("val1") + " and "+ eachMap.get("val2"));
}
}

private static List<Map<String, Integer>> addPairs(int[] inputArr, int addition) {
int i = 0;
int j = inputArr.length-1;
List<Map<String, Integer>> output = new ArrayList<Map<String, Integer>>();
for(; i<j; ) {
Map<String, Integer> outputMap = new HashMap<String, Integer>();
int sum = inputArr[i]+inputArr[j];
if(sum== addition) {
outputMap.put("val1", inputArr[i]);
outputMap.put("val2", inputArr[j]);
i++;
j--;
} else if(sum < addition) {
i++;
continue;
} else {
j--;
continue;
}
output.add(outputMap);
}
return output;
}
}

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

No additional space
complexity < O(n2)

Assumption: The actual array can be changed

void FindPairs(int []A, int length, int s)
{
if(length <= 1) {Console.write("No Pairs. Length is {0}, length}

QuckSort(A);

for (int i =0; i < length; ++i)
{
int v = s - A[i];
if(BinarySearch(A,v)) Console.Write(v);

}

}

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

Algo is right, a little bug while coding. doing a binary search on entire array will be a killer in case sum being searched is double of an element of the array.

e.g. array= 2,3,5,7. sum=6.

- fresh_coder March 07, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

void FindPair(int a[],int x,int i,int j)
{
int n=a.length();

quicksort(a);

int q,w;

q=0;w=n-1;

while(q<w)
{
if(a[q]+a[w]==x)
{
i=a[q];
j=a[w];
return;
}
else if(a[q]+a[w]<x)
q++;
else
w--;
}
//pair not found
i=INT_MIN;
j=INT_MAX;

}

- NaiveCoder March 06, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I got the same question and was asked to in O(n) using hashmap.

- NekDil March 09, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I got the same question and was asked to do in O(n). Did using hashmap.

- NekDil March 09, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

hashmap uses additional space

- mirandaxu789 March 12, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

hashmap uses additional space

- mirandaxu789 March 12, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

#! /usr/bin/perl
use strict;
my $num=$ARGV[0];
my @arr=qw|15 18 6 5 9 1 4 13 16 2|;

print "@arr\n";
for(my $i=2;$i<=scalar(@arr);$i++){
#print $arr[$i],"\n";
my $less=$arr[$i-1];
#print "\tLESS::$less\n";
for(my $j=$i-2;$j>=0;$j--){
#print "\t\t$arr[$j] \+ $less\n";
print "$arr[$j] \+ $less = $num\n" if (($arr[$j]+$less) == $num );
}
}

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

public static int binarySearch(int[] a, int value, int l, int h) {
    if (l <= h) {
      int mid = (l + h) >> 1;
      if (a[mid] == value) {
        return mid;
      } else if (a[mid] > value) {
        return binarySearch(a, value, l, mid - 1);
      } else {
        return binarySearch(a, value, mid + 1, h);
      }
    } else {
      return -1;
    }
  }

  public static void findTwoSumAll(int[] a, int sum) {
    if (a == null) {
      return;
    }
    if (a.length < 2) {
      return;
    }
    for (int i = 0; i < a.length; i++) {
      int otherVal = sum - a[i];
      int otherIdxRight = binarySearch(a, otherVal, i + 1, a.length - 1);
      if (otherIdxRight != -1) {
        System.out.println(a[i] + " - " + a[otherIdxRight] + " at indices: " + i + " - " + otherIdxRight);
      }
    }
  }

- Yue March 24, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

sort the array.
run a loop i starting from index 0 to end.
do a binary search for the other element with starting index = i+1 and last index .
print the values if the sum is k

- Sumit March 13, 2014 | 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