DEV Community

Discussion on: Product of array except self, a mind-boggling Google Interview question

Collapse
 
bitdweller profile image
Pedro Pimenta • Edited

EDIT: I guess I don't know what O(n) is? :)

I am probalby not understanding something, but wouldn't this work?

const baseArray = [1, 2, 3, 4]
const newArray = []

console.log(baseArray)

for (let i in baseArray) {
  let total = 1
  for (let p in baseArray) {
    if (i !== p) {
      total = total * baseArray[p]
    } 
  }
  newArray.push(total)
}

console.log(newArray)

I did it here: jsbin.com/zawuwugagu/edit?js,console

Collapse
 
akhilpokle profile image
Akhil

It works, but your algorithm works in O(n^2). The solution in article works in O(n).

Collapse
 
bitdweller profile image
Pedro Pimenta

Yeah I get it now. I'm not a programmer by education, so I don't know many of these concepts. I guess O(n) means going through the array only once, right? I go through the array as many times as elements are in the array, hence O(n^2). This is not performant, your solution (and the one asked for, actually) is resolved quicker and with less processing power. Hey, I learned something, right? :D Thanks!

Thread Thread
 
akhilpokle profile image
Akhil

Spot on! I will add your solution too so that people like you can get a better idea about performance :D