Amazon Interview Question


Country: United States




Comment hidden because of low score. Click to expand.
1
of 3 vote

import java.util.*;
public class CareerCup{
  public static void printPairs(int[] a){
    HashSet<Integer> hs = new HashSet<Integer>();
    for(Integer i:a){
      hs.add(i);
    }

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

  public static void main(String args[]){
    int[] input = {10, 1, 3, 5, 9, 25, 11};
    printPairs(input);
  }
}

- karim.ainine December 06, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

- daud December 01, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 2 vote

1st Simple solution is:

step 1 - sort the array
	step 2 - for i=0 to len(arr)
				for j=i to len(arr)
					num = arr[i]*arr[j]
					if(search(num,arr))
						store the pair(i,j) //use two dimensional array
				return allStoredPair

- rsingh December 01, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package CareerCup;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class Solution {
public static void main(String[] args) {
int[] A = { 11, 2, 3, 14, 5 };
Map<Integer, Set> pairs = new HashMap<Integer, Set>();
for (int i : A) {
pairs.put(i, new HashSet<Integer>());
}

for (int i = 0; i < A.length; i++) {
for (int j = A.length - 1; j >= 0; j--) {

if (A[i] <= A[j]){
pairs.get(A[i]).add(-A[j] + A[i]);}

if (pairs.get(A[j]).contains(A[j] - A[i]) && pairs.containsKey(A[i])
&& pairs.containsKey(A[i] - A[j])) {

System.out.println((A[j] + " " + (-A[j] + A[i])));
}
}
}
}
}


i couln'd remove duplicates though :(

- amzn_geek December 01, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void Test()
{
int inputArray[] = { 1, 3, 2, 6, 9, 8, 7 };

System.out.print("Input Array : ");
for(int x : inputArray)
System.out.print(x + " ");

System.out.print("\n");

for(int i=0 ; i<inputArray.length; i++)
{
for(int j = i+1; j<inputArray.length; j++ )
{
for(int k=0; k<inputArray.length; k++)
{
if (k != i && k != j)
{
if( inputArray[i] + inputArray[j] == inputArray[k] )
{
System.out.println( inputArray[i] + "+" + inputArray[j] + "=" + inputArray[k] );
}
}
}
}
}
}

- bala December 02, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void Test()
	{
		int inputArray[] = { 1, 3, 2, 6, 9, 8, 7 };
		
		System.out.print("Input Array : ");
		for(int x : inputArray) 
			System.out.print(x + "  ");
		
		System.out.print("\n");
		
		for(int i=0 ; i<inputArray.length; i++)
		{
			for(int j = i+1; j<inputArray.length; j++ )
			{
				for(int k=0; k<inputArray.length; k++)
				{
					if (k != i && k != j)
					{
						if( inputArray[i] + inputArray[j] == inputArray[k] )
						{
							System.out.println( inputArray[i] + "+" + inputArray[j] + "=" + inputArray[k] );
						}
					}
				}
			}
		}
	}

- bala December 02, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

It can be solved in nLogn
Below are the steps
1. Make hashmap
2. sort the array
3. Use 2 pointers approach

- 1Shubhamjoshi1 December 04, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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

/*
 * Given an array of numbers, print all pair (2) of numbers in the array
 * if sum also present in the array
 */
public class ArrayPairSumInArray {

	public static void main(String[] args) {
		int[] iArrays = {1, 3, 2, 6, 9, 8, 7 };	 
		Arrays.sort( iArrays );		
		Set<Integer> set = new HashSet<Integer>();
		for( int num: iArrays ){
			set.add( num );
		}
		for( int i = 2; i < iArrays.length; i++ ){
			for( int j = i - 1; j > 0; j-- ){
				if( set.contains(iArrays[i] - iArrays[j]) && (iArrays[i]-iArrays[j]) < iArrays[j]){
					System.out.println("[ " + ( iArrays[i] - iArrays[j]) + "+" + iArrays[j] + " ] = " + iArrays[i]);
				}
			}
		}
	}

}

- puttappa.raghavendra December 04, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

sorting nlogn algo using binary search with two for loops that is n^2logn

- Anonymous December 21, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Resolver {
        public static IEnumerable <Tuple<int, int>> GetPairs(IEnumerable<int> numbers) {
            var array = numbers.ToArray ();
            if (array.Length < 2) // we don't have pairs!!
                yield break;

            Array.Sort (array);

            if (array.Length == 3) {
                if (array [0] + array [1] == array [2])
                   yield return new Tuple <int, int> (array [0], array [1]);
                // There are no other possibilities due to the fact that the array is sorted!
                yield break;
            }
            
            var hSet = new HashSet <int> (array);

            var lastPosition = array.Length - 1;

            for (var i = 0; i < lastPosition; ++i) {
                // break condition!
                if ((array [i] < 2 ? 2 : array [i] << 1) > array [lastPosition]) {
                    yield break; // we found a situation where we would not find the sum in our array anylonger!
                }

                for (var j = i + 1; j < array.Length; ++j) {
                    var sum = array [i] + array [j];

                    if (hSet.Contains (sum)) {
                        yield return new Tuple <int, int> (array [i], array [j]);
                    }
                }
            }
        }
    }

- aurelian.lica January 07, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
public class PairsWithSumInArray {
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String [] str = br.readLine().split(" ");
        int size = str.length;
        int [] numbers = new int[size];
        for(int i=0; i<size; i++){
            numbers[i] = Integer.parseInt(str[i]);
        }
        List<Triplet> triplets = getAllTriplets(numbers);
        Iterator itr = triplets.iterator();
        while (itr.hasNext()){
            Triplet triplet = (Triplet) itr.next();
            System.out.println(triplet+", value("+numbers[triplet.getA()]+", "+numbers[triplet.getB()]+", "+numbers[triplet.getC()]+")");
        }
    }
    public static List<Triplet>  getAllTriplets(int [] array){
        List<Triplet> triplets = new ArrayList<>();
        HashMap<Integer, Integer> hashMap = new HashMap<>();
        int size = array.length;
        for(int i=0; i<size; i++){
            hashMap.put(array[i], i);
        }
        for(int i=0; i<size-2; i++){
            for(int j=i+1; j<size; j++){
                int a = array[i];
                int b = array[j];
                if(hashMap.containsKey(a+b)){
                    triplets.add(new Triplet(i, j, hashMap.get(a+b)));
                }
            }
        }
        return triplets;
    }
}
class Triplet{
    private int a;
    private int b;
    private int c;

    public Triplet(int a, int b, int c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    public int getA() {
        return a;
    }

    public int getB() {
        return b;
    }

    public int getC() {
        return c;
    }

    @Override
    public String toString() {
        return "Index"+"("+a+","+b+","+c+")";
    }

}

- neelabhsingh January 25, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 3 vote

This can be solved in O(n^2) time complexity and O(n) space complexity.
1) Create a hashmap with all the elements in the array
2) Use two for loops to get the sum for each pairs and check if the sum is present in the hashmap.

Can anyone provide feedback on how to improve this algorithm?

- Rahul December 01, 2016 | 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