Time complexity nuances in JavaScript

Viewed 69

What is the time complexity of the algorithm below ? I suppose it's O(n), because of traversing through the array and O(n), because of reversing array. All in all it's O(2n) -> O(n). Am i right ?

I tried to avoid the one-line brute force approach, which is simple .map().sort() -> O(nlog(n)), by creating the following algorithm.

function sortedSquaredArray(array) {
    const sortedSquared = [];
    let startIdx = 0;
    let endIdx = array.length - 1;

    for (let i = 0; i < array.length; i++) {
        if (Math.abs(array[startIdx]) > Math.abs(array[endIdx])) {
            sortedSquared.push(array[startIdx] ** 2);
            startIdx++;
        } else {
            sortedSquared.push(array[endIdx] ** 2);
            endIdx--;
        }
    }
    return sortedSquared.reverse();
}

Another question is about chaining methods, like in the algorithm below. Is it right that these chaining methods ran asynchronously, not concurrently ? One method doesn't run until the previous one completes. So it's .filter() -> O(n), .map() -> O(n), .reduce() -> O(n). That gives us O(3n) -> O(n). Correct me if I'm wrong :)

function foo(arr) {
    return arr
        .filter((digit) => digit % 2 === 0)
        .map((digit) => digit ** digit)
        .reduce((total, item) => total + item);
}
0 Answers
Related