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

433
Visualizações
Weird Leetcode Bug: Array.fill() vs new Array.from()

I was working on Leetcode Problem 1770 and ran into some weird behavior that I'm hoping someone can help me understand.

It's a dynamic programming problem that requires you to instantiate a 2-dimensional array of length m. Pretty straightforward.

What's weird is that my syntax for generating a 2D array causes the problem to fail, but an alternative syntax passes all tests. As far as I can tell the two lines output an identical result.

My syntax:

//  const m = 3

    let memo = new Array(m).fill(new Array(m).fill(-Infinity))
    console.log({memo})

//  stdout: {
//    memo: [
//      [ -Infinity, -Infinity, -Infinity ],
//      [ -Infinity, -Infinity, -Infinity ],
//      [ -Infinity, -Infinity, -Infinity ]
//    ]
//  }

Alternative syntax:

//  const m = 3

    let memo = Array.from(Array(m), () => Array(m).fill(-Infinity))
    console.log({memo})

//  stdout: {
//    memo: [
//      [ -Infinity, -Infinity, -Infinity ],
//      [ -Infinity, -Infinity, -Infinity ],
//      [ -Infinity, -Infinity, -Infinity ]
//    ]
//  }

To my eye the output of the two is exactly identical. Yet one passes all tests and what doesn't. What gives?

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

0

In the first case you are filling the array with the same Array instance. In the second case every row is a new Array because you provided a factory function.

const m = 3;

let memo = new Array(m).fill(new Array(m).fill(-Infinity));

console.log(memo[0] === memo[1]); // true

const m = 3

let memo = Array.from(Array(m), () => Array(m).fill(-Infinity));

console.log(memo[0] === memo[1]); // false

As a side note, you don't need to pass an Array as the first parameter of Array.from, an ArrayLike is enough:

const m = 3

let memo = Array.from({ length: m }, () => Array(m).fill(-Infinity));

console.log(memo);

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