Ace your interviews with Exponent’s Software Engineering interview course: bit.ly/3UwzFMv
@King-ul4nb6 ай бұрын
I wish such easy questions were asked in my interviews
@andrehil3 ай бұрын
Correct me if I'm wrong, but no solution presented here had space complexity O(1) as mentioned. That would mean creating no array. Since all solutions created at least an output array, that's O(n). The ones that created more than one were 2n or 3n; some people argue that you can skip the number in that case, which I personally dislike as 2n is twice as much space or time, therefore, not insignificant. The same applies to time when there was more than one for loop.
@merottm3 ай бұрын
Here's a solution with O(1) constant space and O(n) time complexity, written in TypeScript: function productAllExceptI(arr: number[]) { let allProduct = 1 let zerosCount = 0 for (const num of arr) { if (num !== 0) allProduct *= num else zerosCount++ if (zerosCount > 1) break // it'll all be 0 anyway, we can stop multiplying } for (let i = 0; i < arr.length; i++) { if (zerosCount > 1) arr[i] = 0 else if (arr[i] === 0) arr[i] = allProduct else if (zerosCount === 1) arr[i] = 0 else arr[i] = allProduct / arr[i] } return arr }
@recentvisit6 ай бұрын
What about my solution? const getProductArray = (array: number[]): number[] => { const outputArray: number[] = []; for(let i = 0; i < array.length; i ++) { let prod = 1; for(let j = 0; j < array.length; j ++) { if (i !== j) prod*=array[j]; } outputArray.push(prod); } return outputArray }
@JoeEverest1656 ай бұрын
Anytime you have to put a loop inside another loop, take a second to think about some optimization you could do. In this case, why not calculate the product of all items in the array and store it. Then divide by each instance of i