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

106
Visualizações
Understanding time complexity to replace string characters

This is my solution in javascript to remove all occurrences of 'b' and 'ac' in a string but I am able to come up with time complexity esp. when removing all occurences for 'ac'. Could someone explain ?

function removeChars(input) {
  let result = input;

  
  result = result.replaceAll('b', '');   // tc = O(n) where n is length of string. string of all b's
  

  while(result.indexOf('ac') !== -1) {  // number of ac ? what if aacacacc
    result = result.replaceAll('ac', '');    // replaceAll has time complexity of O(n)
  }
  return result;  // space ~ O(n)
}

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

We can consider one of the most special cases: input = aaa...aaaccc...ccc.

Assume the input string has length n, there will be n / 2 occurences for 'ac'. The statement of result = result.replaceAll('ac', ''); will be executed n / 2 times. The time complexity of replaceAll() is O(n), thus the overall time complexity is O(n^2).

about 4 years ago · Santiago Trujillo Relatório

0

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present, so the worst case will be O(N), and you replaceAll inside the loop so the Big-O is O(N), the total Will O(N^2)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

about 4 years ago · Santiago Trujillo 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