Skip to content

Instantly share code, notes, and snippets.

@kevinwucodes
Last active October 17, 2020 15:42
Show Gist options
  • Save kevinwucodes/6cc7f13c01d606b55e0128aaa7193765 to your computer and use it in GitHub Desktop.
Save kevinwucodes/6cc7f13c01d606b55e0128aaa7193765 to your computer and use it in GitHub Desktop.
daily coding problem #2: Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.

This problem was asked by Uber.

Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.

For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].

function aryTransform(input) {
  return input.map((el, index, ary) => {
    const everything = ary.reduce((acc, curr) => {
      return acc * curr
    })
    return everything / el
  })
}

console.log(aryTransform([1,2,3,4,5]))  //[ 120, 60, 40, 30, 24 ]
console.log(aryTransform([3,2,1]))  //[ 2, 3, 6 ]

Follow-up: what if you can't use division?

function aryTransformWIthoutDivision(input) {
  return input.map((el, index, ary) => {
    return ary.reduce((acc, curr, rIndex) => {
      if (curr == el) {
        return acc
      } else {
        return acc * curr
      }
    }, 1)
  })
}

console.log(aryTransformWIthoutDivision([1,2,3,4,5])) //[ 120, 60, 40, 30, 24 ]
console.log(aryTransformWIthoutDivision([3,2,1])) //[ 2, 3, 6 ]
@NOURELsayed
Copy link

Hello, I tried to solve it with for loop but it doesn't work clearly, could you please tell what's wrong and how I can fix that

function arraySumtionWithoutI(arr){
for(var i=1; i<= arr.length; i++){
var newArr = arr.reduce((a,b) => {
return a*b
})
console.log(newArr/i)

// return newArr/i

}
}
console.log(arraySumtionWithoutI([1, 2, 3, 4, 5]))
console.log(arraySumtionWithoutI([3, 2, 1]))

@kevinwucodes
Copy link
Author

I think it's working? What do you think is wrong with your solution?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment