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

127
Views
String trimming: Performance of while loop vs Binary Search?

The standard way of trimming some characters of a string, would be to loop through each character from left to right (or right to left depending on l or r trim) and then slice it. This should have worst-case complexity O(n), if n is the length of the string, but what really matters here is how many to-be-trimmed characters I have. If I have x, it'll be O(x).

I was thinking: If I wanted to trim A TON of strings, do you think it would be possible to improve on that performance by doing a binary search? It would definitely improve worst-case runtime to O(logn), but what I'm not so sure about is whether it would improve average case runtime. How can I analyze my runtime with respect to x instead of n here?

For the implementation, I thought of simply having (For left trim):

leftTrim(str, start, end, i):
    if end-start == 2:
        return str[i] is trimChar ? i : -1
    if str[i] is trimChar:
        leftTrim(str, i, end, i + (end-start)/2)
    else:
        leftTrim(str, start, i, i/2)
leftTrim(str, 0, str.length, str.length/2)

Although it looks a little bit overcomplicated to me, it should work, right?

about 4 years ago · Juan Pablo Isaza
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!