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

109
Visualizações
does indexOf() in JS search all the elements of an array to execute?
const arr = ['a','b','c']; 
for (let char of arr) {
  console.log(char);
}

I believe that time complexity of code above is O(n).

const arr = ['a','b','c']; 
for (let char of arr) {
  console.log(arr.indexOf(char);
}

However, does indexOf() search all the elements? If does so, I believe time complexity of code above may be O(n^2)

I want to know whether indexOf() searches all the components as for loop or not.

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

0

For time complexity, you always consider the worst case (for the OP's circumstance, each character is in the list at no specifically designated position). To take OP example array, doing arr.indexOf('c') would involve looking at every position until the character c is found (which is the last position). Therefore, assuming worst case scenario, the execution would take O(n) time for .indexOf(). As per @Nick Parsons comment, there are ways to improve the time of the underlying search algorithm using strategies like a binary search (which is O(log n) time complexity), but that implies the data is in some semi-structured format for any concepts like binary search to improve the time complexity.

about 4 years ago · Juan Pablo Isaza Relatório

0

If the browser vendors follow the language specification, then the answer is NO. It should return once a match is found. Under certain circumstances, it will return even without checking any elements. See ECMA262.

However, complexity would be the same, O(n^2).

about 4 years ago · Juan Pablo Isaza Relatório

0

Yes, the indexOf() function has a complexity of O(n). If the provided index is negative, the array is still searched from front to back. If the calculated index is less than 0, then the whole array will be searched.

So your program will have big o notation of O(n^2)

You can find more about this here at MDN

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