String Incrementer Codewars Kata Solution

Your job is to write a function which increments a string, to create a new string.

  • If the string already ends with a number, the number should be incremented by 1.
  • If the string does not end with a number. the number 1 should be appended to the new string.
Examples:

foo -> foo1

foobar23 -> foobar24

foo0042 -> foo0043

foo9 -> foo10

foo099 -> foo100
Attention: If the number has leading zeros the amount of digits should be considered. Codewars

JavaScript Brute Force

Dropping the constants, the run time complexity of this algorithm is linearO(n).

  1. str.slice() = O(1)
  2. …match() = O(n)
  3. the return conditions = O(n)

A better regex can definitely drop some of these constants:

Optimized Solution

Kotlin Solution

In Kotlin the replace function creates a MatchReslut type, that represents all the string matches.

But the JS optimized solution, we dropped the JavaScript match() function which creates an array of matched characters. Instead, we use the replace function with a replacer function callback. This way we don’t need to run again over the matched elements, but we run over the element once it was found.

chevron_left
chevron_right

Leave a comment

Your email address will not be published. Required fields are marked *

Comment
Name
Email
Website