Separate the Numbers

  • + 0 comments

    If you understand the main idea behind this problem, then the solution is easy. We have to figure out two things:

    1. The correct starting number (first_num)
    2. Whether the string forms a beautiful sequence from that starting number.

    Algo:

    Iterate through the string and try every possible starting number by taking its prefix.

    *for i in range(1, len(s) // 2 + 1):  # Try every possible length for firstnum
        firstnum = int(s[:i])           # Guess the first number
        nextnum = firstnum + 1         # The next expected number in sequence
        temp = s[:i]                     # Start building the sequence from firstnum*
    

    Now simulate building the sequence by adding next numbers:

    *
        while len(temp) < len(s):        # While our built string is shorter than the original
            temp += str(nextnum)        # Append the next number
            nextnum += 1                # Move to the next*
    

    Finally, check if the built string matches the original:

    *    if temp == s:
            print("YES", firstnum)
            return
    *
    

    If no such starting number worked, then the string isn’t beautiful:

    print("NO")