Problem statement

https://binarysearch.com/problems/Maximum-Number-by-Inserting-Five/

Solution

It is enough to make bruteforce here. However we can do better. If number is positive, we need to find the first digit < 5 and for the negative number we need to find the first digit > 5.

Complexity

It is O(k) for time and space, where k = len(str(n))

Code

class Solution:
    def solve(self, n):
        digits = list(str(n))
        k = len(digits)

        if n >= 0:
            i = 0
            while i < k and int(digits[i]) >= 5: i += 1
        else:
            i = 1
            while i < k and int(digits[i]) <= 5: i += 1

        return int("".join(digits[:i]) + "5" + "".join(digits[i:]))