'If I call a function that contains a for loop inside a for loop, is that considered O(n^2) time or O(n)?
for loop inside subArraySum calls sumArray which also contains a for loop. Would this be considered O(n^2) time? Go easy on me as this is my first ever question and as you can see from my code, I'm a beginner. This is my code:
const subArraySum = (arr,n) => {
let i = 0;
let result = [];
for (let j = n-1;j<arr.length;j++) {
let li = arr.slice(i,j+1);
result.push(sumArray(li));
i++;
}
return maxResult(result);
}
function sumArray(li) {
counter = 0;
for (let k of li) {
counter+=k;
}
return counter;
}
function maxResult(result) {
let highest = 0;
for (let k of result) {
if (k>highest) {
highest = k;
}
}
return highest;
}
Solution 1:[1]
Yes, this makes it O(n^2), since complexity applies to the entire algorithm, not matter how it's split up into functions. Moving some code out to a named function doesn't change the overall running time or how it depends on the input.
Sometimes when we're calling built-in functions of the language or OS we may treat them as black boxes whose complexity is unknown, so we may ignore them for the purpose of calculating the complexity of our own algorithm. But you can't usually ignore the complexity of your own functions that form part of your algorithm, since you have the option of redesigning them if there's a more efficient way.
Solution 2:[2]
It totally Depends on what kind of approach you're using inside of each for loop.
let us take simple example:-
if you're taking an a for loop which increments linearly (increments constantly till condition works) and inside it (in body) has a calling function which also has another linear for loop in it's body.
so, the time complexity will be O(n^2). The second for loop will iterate through n for each call of the function by each iteration of the first for loop. But it totally depends on what kind of incremental approach and conditions (any) you have for both for loop.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Ajay Kachhela |
