Amazon Interview Question: Given an array of integers [1... | Glassdoor.ie

Interview Question

Software Development Engineer I Intern Interview Dublin, Co. Dublin

Given an array of integers [1,2,3,4]. and target t

  = 5. Come up with a solution that will print out all the unique pairs in the array that are equal t.
Answer

Interview Answer

3 Answers

0

Found this very hard, but the interviewer gave subtle hints, and I eventually came up with the idea of using a nested for loop. But I was not completely correct as I had set the inner incrementer to j = 0 instead of j = i+1 .

Interview Candidate on 3 Oct 2015
0

array a=new array();
foreach(int i in a)
{
if(i==t)
{
console.writeline(i.toString());
}
}
//c# code,i am not sure if this is what they whanted

Anonymous on 17 Apr 2017
0

public class CalculateTuple {

    /**
     * @param args
     */
    public static void main(final String[] args) {
        final int arr[] = { 1, 2, 3, 4 };
        final int sum = 5;
        solution(arr, sum, false);

    }

    /**
     * find possible tuple for provided sum
     *
     * @param input
     * input array
     * @param expectedSum
     * expected sum value for the tuple
     * @param isCommutative
     * true : (1,2) != (2,1) will give you both tuple <br>
     * false : (1,2) == (2,1) are same and give you only (1,2)
     */
    public static void solution(final int input[], final int expectedSum, final boolean isCommutative) {
        final Map indexedArray = new HashMap();
        final Map uniquePair = new HashMap();

        final int length = input.length;
        for (int i = 0; i &lt; length; i++) {
            indexedArray.put(input[i], i);
        }

        int count = 0;
        for (int i = 0; i &lt; length; i++) {
            final Integer integer = indexedArray.get(expectedSum - input[i]);
            if (integer != null &amp;&amp; integer != i) {

                if (isCommutative
                        || (null == uniquePair.get("(" + i + "," + integer + ")") &amp;&amp; null == uniquePair.get("(" + integer + "," + i + ")"))) {
                    System.out.println("(" + i + "," + integer + ")");
                    uniquePair.put("(" + i + "," + integer + ")", "(" + i + "," + integer + ")");
                    count++;
                }

            }

        }

        System.out.println("Found " + count);
    }
}

Anonymous on 22 Nov 2017

Add Answers or Comments

To comment on this, Sign In or Sign Up.