2
arr.sort((a, b) => a - b).map(num => num ** 2);

What would be a Big O of the following operation?

As I understand Big O of imbedded sort function in JS is O(Nlog(N)) and Big O of map is O(N), therefore Big O is O(Nlog(N))?

Konstantink1
  • 575
  • 1
  • 8
  • 26

1 Answers1

6

The complexity of your function f, for arr of size n. We'll assume:

arr.sort ∈ O(nlogn)
arr.map ∈ O(n),

We can just sum these terms, since these operations are done serially (one after the other. Thus,

f(n) ∈ O(nlogn + n)

Note that the nlogn term will grow slowly, but eventually:

as n -> infinity, nlogn >> n
thus, as n -> infinity, nlogn + n -> nlogn

So we can simplify to just O(nlogn) for sufficiently large n.

All of this is to say, yep, you got it.

CollinD
  • 7,304
  • 2
  • 22
  • 45
  • 1
    Agreed, since they are running in series, one after the other, you would add O() for each. – mykaf Oct 28 '21 at 17:16
  • 2
    That's a great point of clarification that I left out, thank you! Very important to note that these operations are in no way nested, so we can just add up terms. – CollinD Oct 28 '21 at 17:16
  • Thank you very much! I guess I have a follow up question: If I have a function where I'm supposed to perform such operation on 2 arrays (not nested), then it will be O(nlogn + nlogn) => O(2nlogn), where 2 will be ignored since it is constant and therefore the whole wrapper function will be O(nlogn)? Basically as long as it is no functions nested inside each other it will not escalate to being quadratic, right? – Konstantink1 Oct 28 '21 at 17:27
  • 1
    @Konstantink1 Yeah absolutely. Constant terms can be eliminated, and you'll only end up with a quadratic if you can find a quadratic term to squash the nlogn term (often seen in, ex doubly nested variable-length loops). I'd suggest trying to understand the formal definition of big-oh notation on wikipedia and do some exercises trying to find specific values for constant terms, minimum n values etc with some of your own code. – CollinD Oct 28 '21 at 21:19