Advertisement
makispaiktis

DCP2 - Product in an array

Aug 19th, 2020 (edited)
1,217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Good morning! Here's your coding interview problem for today.
  2. // This problem was asked by Uber.
  3. // Given an array of integers, return a new array such that each element at index i of the new array
  4. // is the product of all the numbers in the original array except the one at i.
  5. // For example, if our input was [1, 2, 3, 4, 5], the expected output would be
  6. // [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].
  7.  
  8. function productArray(arr){
  9.     let prod = 1;
  10.     for(let i=0; i<arr.length; i++){
  11.         prod *= arr[i];
  12.     }
  13.     let newArr = []
  14.     for(let i=0; i<arr.length; i++){
  15.         newArr.push(prod / arr[i]);
  16.     }
  17.     return newArr;
  18. }
  19.  
  20. // MAIN FUNCTION
  21. console.log();
  22. arr1 = [1, 2, 3, 4, 5];
  23. console.log(productArray(arr1));
  24. arr1 = [10, 31, 43, 24, 58];
  25. console.log(productArray(arr1));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement