Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

268
Visualizações
JavaScript flatten array: are the two approaches the same in terms of the time complexity?

I am aware that an array method flat exists. but I would like to get a better understanding on how ... and concat affect the time complexity.

function flat1(arr) {
  return arr.reduce(
    (flatArr, item) => {
      flatArr.push(...(Array.isArray(item) ? flat1(item) : [item]))
      return flatArr
    },
    []
  )
}

function flat2(arr) {
    return arr.reduce(
      (flatArr, item) => {
        return flatArr.concat(Array.isArray(item) ? flat2(item) : item)
      },
      []
    )
  }
  

My intuition is that both approaches take O(n^2) time complexity worse case, n being the number of item in the original array. Because both concat and ... are going to iterate through the array and it is going to take n for both operation. Is my understanding right?

Is one approach preferred over the other approach?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I will need to simplify the problem by not flattening recursively, but only a single level:

function flat1(arr) {
  return arr.reduce((flatArr, item) => {
    flatArr.push(...(Array.isArray(item) ? item : [item]))
    return flatArr
  }, [])
}

function flat2(arr) {
  return arr.reduce((flatArr, item) => {
    return flatArr.concat(Array.isArray(item) ? item : [item])
  }, [])
}

Let's assume the number of elements in arr is n, and the average number of elements in each item array is m. (And items that are not arrays count into that average as 1).

both concat and ... are going to iterate through the array

Yes, they both need to iterate through the item given to them. But that is not the point. push does modify the flatArr and takes O(m) time to add O(m) new elements onto it.

However, concat does create a new array, and for that it does not need to only iterate item but also flatArr. Given flatArr contains on average O(n/2*m) items, the flatArr.concat(item) takes O(n/2*m + m) = O(n*m).

Since each of these operations is executed once for each item in the arr, we get

  • for flat1 the time complexity O(n*m) and
  • for flat2 the time complexity O(n*n*m) which is worse.

The time complexities of the recursive functions are way more complicated since they also depend on how many arrays you have on which nesting levels. I'm failing to even come up with a good metric to describe such data structure :-)

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda