Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

104
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!