Search code examples
algorithmcallbacktime-complexitybig-ospace-complexity

How do you calculate time complexity for a function that has function within?


I'm not sure if it's suitable to ask such a basic question but I was just wondering how to calculate a function that has another function inside.

From my understanding of Big O notation, if there are only multiple non-nested for loop, then it's O(n), and depending on the number of nesting loops, it increases by n squared.

but how about a function like below when there's a helper function within a function along with while loop and for loop.

function solution(nums) {
  let container = [];
  let zero = 0;
  let one = 1;
  let two = 2;
  let answer = 0;

  function isPrime(n) {
    for (let i = 2; i < n; i++) {
      if (n % i === 0) {
        return false;
      }
    }
    return true;
  }

  while (nums) {
    container.push(nums[zero] + nums[one] + nums[two]);
    two++;
    if (two === nums.length) (one++, two = one + 1);
    if (one === nums.length -1) (zero++, one = zero + 1, two = one + 1);
    if (zero === nums.length-2) break;
  }
  for (let i = 0; i < container.length; i++) {
    if (isPrime(container[i]) === true) answer++;
  }
  return answer;
}

I've read few articles about it and I'm guessing the above function is O(n log n)? I'm sorry for asking this question. I'm a beginner and I don't have a community or anybody to ask. I've always heard this place is "the" place to get programming question answers.

Thanks in advance!!


Solution

  • The complexity is O(n^2).

    The inner function's (isPrime()) complexity itself is O(i), where i is its input.

    Since isPrime() is called for each value in the container, and the container contains O(n) elements, after being filled up in previous loop, the total number of operations it is going to do is: O(1 + 2 + 3 + ... + n).

    Now, 1 + 2 + .... + n is Sum of arithmetic progression, and itself is in O(n^2), thus your solution() is O(n^2).