I have a problem to determine the complexity of my algorithm because it use features of ES6 and of course they are chained methods. I already know some of basic complexity of those method for example the complexity of Array.prototype.map is O(n). But when we want to determine a complexity of an algorithm, how do we manage chained method ?
For example, consider we have a function which return for an array the sum of its positive numbers
let sumPositive = arr => arr.filter(i => i > 0).reduce((a, b) => a + b, 0);
console.log(sumPositive([1, 2, 3, -4])); // 6
console.log(sumPositive([1, 2, 3, 4])); // 10
Therefore, what is the complexity of that function ?
Another example is this algorithm which for a given string, return the counts of each character in the string
let charCount = str => str.split('').map(
(c,_,str) => str.filter(i => i===c)
).reduce((a, b) => a.hasOwnProperty(b[0]) ? a : ({...a, [b[0]]: b.length}), {});
console.log(charCount("hi")); // {"h": 1, "i": 1}
console.log(charCount("hello to you")); // {"h": 1, "e": 1, "l": 2, "o": 3, " ": 2, "t": 1, "y": 1, "u": 1}
So for this second I need to know especially its complexity because we are dealing with nested method like the filter which is being call inside a map
So any general method to determine the complexity of such algorithm are welcome.
Note: All the complexity in this question is the time-complexity not space
Thanks
Chaining methods is actually just for convenience. map() or filter() returns an array. Now you can first put a name on the array, like let result = arr.map(...) and then do other stuff on that result array, or you can directly do something on the array returned by map() (or filter()), like map().filter().<more chaining if you want>.
So, it's equivalent to a sequential execution. Consider this example,
let sumPositive = arr => arr.filter(i => i > 0)
.reduce((a, b) => a + b, 0);
let arr = [1, 2, 3, -4];
let filteredArray = arr.filter(i => i > 0); // O(n)
let reducedResult = filteredArray.reduce((a, b) => a + b, 0); // O(n)
console.log(sumPositive(arr)); // 6
console.log(reducedResult) // 6
Now you see filter() takes O(n) and then reduce() takes O(n), so you get O(n) + O(n) ==> O(n) as your final time complexity.
I hope you can similarly find complexity for the second example. If you need assistance, let me know in the comments.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With