0

I am working through creating a flatten function on my own and I came up with this:

function flatten(newArr, result = []) {
   for (let x = 0; x < newArr.length; x++) {
      if (Array.isArray(newArr[x])) {
         flatten(newArr[x], result) 
      } else {
         result.push(newArr[x])
      }
   }
     return result
}

Are there any pitfalls here that I am missing? I assume the big O would be O(n) since this is a linear loop that depends on the numb

  • but its recursive - its not `o(n)` – Daniel A. White Jan 05 '21 at 21:56
  • https://stackoverflow.com/questions/13467674/determining-complexity-for-recursive-functions-big-o-notation – Daniel A. White Jan 05 '21 at 21:57
  • 1
    I think it will be O(N), where N is total number of elements (including nested arrays). It's recursive, but it only 'touches' every element once. – Voodu Jan 05 '21 at 21:59
  • 1
    This was a variadic complexity, that tend to O(n ** k) where k is de deep of arrays that are merging with your elements. If we have a function that flattlen 1 level of deep, and each element of nested 1 level has the same numbers of element k, we have O(n * k). This function are dinamically chaining deep arrays, this can be a hard problem to determine the complexity, because dependes of your input. – Daniel Farina Jan 05 '21 at 22:22

0 Answers0