Your job is to write a function which increments a string, to create a new string.
Examples:
- 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.
Attention: If the number has leading zeros the amount of digits should be considered. Codewarsfoo -> foo1 foobar23 -> foobar24 foo0042 -> foo0043 foo9 -> foo10 foo099 -> foo100
JavaScript Brute Force
Dropping the constants, the run time complexity of this algorithm is linear – O(n).
- str.slice() = O(1)
- …match() = O(n)
- 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.