For an interview, they ask me to do some exercises and the 3rd one was the following:
We have an unknown quantity of elements in a vector/array v1 with random integer numbers.
- Made a v2 vector/array with the same length of v1 in that the v2[k] is the product of all the elements of v1 except v1[k]
- try to do it without the division operator and with complexity O(n).
And I do the following code:
const v1 = [4, 2, 7, 8, 6, 7, 9, 3, 2, 6, 7]; //it's just an example array
const l = v1.length;
let v2 = [];
for (let i = 0; i < l; i++) {
let segment = v1.splice(0, 1); // save the number of the position in array that it'll exclude de product
let product = v1.reduce((total, number) => { return total * number; }, 1);
v2.push(product); // add the result to the v2 array at the position of the number of v1 array
v1.push(segment); // is necesary to add again the segment of the v1 array to keep the original length
}
console.log('v2', v2);
/* Results Reference
product of all array 42674688
product - position 00 10668672
product - position 01 21337344
product - position 02 6096384
product - position 03 5334336
product - position 04 7112448
product - position 05 6096384
product - position 06 4741632
product - position 07 14224896
product - position 08 21337344
product - position 09 7112448
product - position 10 6096384
*/
My question is:
- Is my code an O(n) complexity? or is O(n^2)? or another kind of complexity?
thanks
segmentthen pushed it again? Did you think aboutfilter?filterit could gain complexity ap to n^2