Wallet Hub interview question

Given an array of numbers, create another array of numbers. Calculate each new array number by multiplying all input array numbers, except for the current number position in the new array.

Interview Answers

Anonymous

14 Nov 2017

Solution with O(N) public long[] multipliedArray(int[] arr){ long result[] = new long[arr.length]; long allMultiplication=1; for(int i=0;i

3

Anonymous

6 Dec 2017

public static void main(String[] args) { int[] returnVal = multiplyArrayItems(new int[]{1,2,3,4,5}); System.out.println(String.join(",", Arrays.stream(returnVal).mapToObj(String::valueOf).toArray(String[]::new))); } static int[] multiplyArrayItemsSE(int[] arr){ int[] returnArr = new int[arr.length]; ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("js"); try { String[] sarr = Arrays.stream(arr).mapToObj(String::valueOf).toArray(String[]::new); int totalVal = (int) engine.eval[String.join("*", sarr)); for(int i = 0; i < arr.length; i++){ returnArr[i] = totalVal / arr[i]; } } catch (ScriptException e) { // TODO Auto-generated catch block e.printStackTrace(); } return returnArr; }

Anonymous

2 Nov 2017

A O(2*N) = O(N) solution would include: 1. Get the product of all the numbers in the input array; 2. Set the ith number as the product, in step1, divided by the ith number in the input; Of course, the obvious solution would have complexity of O(n^2): get the new array ith number by getting the product of all the input numbers except for the ith position number.