Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can you tell me what is the runtime complexity of this algo?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
};

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading