Visa Inc.

  www.visa.com
  www.visa.com

Interview Question

Senior Software Engineer Interview

Given an array of integers, return an array where each

  respective location contains the product of the numbers except the one that occupied this same location in the input array. Thus, given in={1,2,3}, out={6,3,2}.
Answer

Interview Answer

2 Answers

0

import org.junit.Assert;

import org.junit.Test;

public class ArrayMultiplication
{
    @Test
    public void arrayMultiplication() {
        int[] inputArray = {1,2,3};
        int[] expectedArray = {6,3,2};
        int[] outputArray = new int[inputArray.length];
        for(int i = 0; i < inputArray.length;i++) {
            int product = 1;
            for(int j = 0; j < inputArray.length; j++) {
                if(i == j) continue;
                product = product * inputArray[j];
            }
            outputArray[i] = product;
        }
        Assert.assertArrayEquals(expectedArray, outputArray);
    }
}

Anonymous on Sep 16, 2014
0

Multiply the entire array in a single pass. Then traverse through the array again and divide by the number at the index position. O(n)

Arundhati Jaswal on Dec 9, 2014

Add Answers or Comments

To comment on this, Sign In or Sign Up.