0

For example,

const arr = [1,2,3]
let multipliedByTwos = [...arr].map(n=>n*2)

I'm wondering what's the time complexity to produce multipledByTwos.

I know spreading [...arr] is O(N), and .map() in this case is also O(N). But what if they're chained together like the code example above? I assume still O(N)? Because it spreads first (O(N)) and then maps it (O(N)).

Something like this O(N) + O(N) === 2O(N), which really is just O(N). Is this correct? Or should it be O(N^2) because the chaining actually multiplies the time complexity rather than adding them? I'm kinda lost a bit in this concept.

EDIT: Im not asking whether O(N) * 2 is O(N). But im asking about my general understanding of the chaining of [...arr] and .map().

Thanks.

Sean Saoirse
  • 91
  • 5
  • 17
  • "*Something like this O(N) + O(N) === 2O(N), which really is just O(N). Is this correct?*" Yes. Easy to prove - the number of visited elements will grow *linearly*. If you have 3 items in the array, you visit 2*3=6. If you have 30 items, it's 2*30=60. "*Or should it be O(N^2)*" does adding more elements mean you visit *increasingly more than the added amount*? No. – VLAZ Feb 05 '22 at 16:53
  • Side note: You can avoid the second pass by using `Array.from(arr, n => n * 2)`, which does the building of a new array and the mapping in a single pass. But I don't think the question is really about that so much as about time complexity. :-) – T.J. Crowder Feb 05 '22 at 16:53
  • if we do the same with just for loops it would be O(N) so.. – cmgchess Feb 05 '22 at 16:54
  • 1
    "*Im not asking whether O(N) * 2 is O(N). But im asking about my general understanding of the chaining of [...arr] and .map().*" spreading is `O(n)` and `.map()` is also `O(n)`. I don't see how you can reasonably assume that they don't just do two separate `O(n)` operations. To have quadratic complexity, you'd have to somehow run `.map()` for every element spread or something along those lines. What operation do you expect happens that would cause non-linear complexity when the two operations are chained? – VLAZ Feb 05 '22 at 16:59
  • @VLAZ I understood your first comment. It was just to make it clear because somehow SO flagged it as duplicate to a question asking O(n) + O(n) = O(n) - which is NOT what im asking, clearly :). Thx for ur answer tho – Sean Saoirse Feb 05 '22 at 17:01

0 Answers0