2

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);
}
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • 1
    It's better to ask one question at a time. Asking more than one makes providing answers more complicated. As to the second question, the three chained methods do not run asynchronously and they do not run concurrently; they run sequentially. – Pointy Jul 13 '21 at 13:05
  • So how does this transfer to the time complexity of the algorithms ? – pawlovskiii Jul 13 '21 at 13:07
  • 1
    This is all correct, except that we wouldn't call that "asynchronously", but "synchronously". The terms have quite specific meanings in the JavaScript world. Synchronous means that code executes in order, only using the call stack. Asynchronous means that code is not executed immediately but is scheduled to run once the call stack is empty (or even later): the key is that asynchronous code gets executed by the event loop. This is not happening in your code. – trincot Jul 13 '21 at 13:08
  • 1
    I think your "big-O" analysis is correct. – Pointy Jul 13 '21 at 13:12
  • 1
    @pawlovskiii Async vs sync has no impact on time complexity. Even parallelism has no impact. – Barmar Jul 13 '21 at 13:19
  • "*I tried to avoid the one-line brute force approach, which is simple .map().sort()*" - it's unclear what your `sortedSquaredArray` is supposed to do. Notice it does not correctly sort all arrays. – Bergi Jul 13 '21 at 15:55

0 Answers0