0

This function simply takes multidimensional array and makes it flat

for example flatArray([1,[1,2,4,[2,3]],1]) -> [1,1,2,4,2,3,1]

I would like to know what time complexity this algorithm has.

let flatArray = function(numsArr){
    let container = [];
        for(let i = 0;i<numsArr.length;i++){
            if(Array.isArray(numsArr[i])){
                container = [...container,...flatArray(numsArr[i])]
            }else{
                container.push(numsArr[i])
            }
            counter ++
        }
    return container;
};

1 Answers1

1

Your function takes O(n2) time. The worst case is something like [1,[2,[3,[4,[5,[6...]]]]]], where each element will be copied into a new list n-1 times.

To implement this function in O(n) time, you have to avoid all the copying:

let flatArray = function(numsArr){
    let container = [];
    function addArray(arr) {
      for (const val of arr) {
        if (Array.isArray(val)) {
            addArray(val);
        } else {
            container.push(val);
        }
      }
    }
    addArray(numsArr);
    return container;
}
Matt Timmermans
  • 53,709
  • 3
  • 46
  • 87