Separate the Numbers : HackerRank Solution in Python

Shounak Lohokare
2 min readJan 30, 2021

Solution in Python 3

def separateNumbers(s):    if len(s)==1:
print("NO")
return
for i in range(1, len(s)//2+1): genstr = s[:i]
prev = int(genstr)
while len(genstr) < len(s): next = prev+1
genstr+=str(next)
prev = next
if genstr == s:
print("YES", s[:i])
return
print("NO")

Explanation

First, we will check the edge case, If length of s is equals to 1 then the numeric string can not be beautiful hence we print NO.

if len(s)==1:
print("NO")
return

Instead of determining whether the given numeric string is beautiful or not by slicing it or performing other operations on it directly, we will make a valid beautiful string of our own and equate it with given numeric.

To make a beautiful numeric string of our own, We use a for loop to iterate from 1 to the half of the length of s

for i in range(1, len(s)//2+1):

Once inside the for loop, we declare a variable genstr and assign s[:i] to it. If the s = “91011" and i = 3 then s[:i]=”910”. Then we declare another variable prev and assign int(genstr) to it.

for i in range(1, len(s)//2+1):
genstr = s[:i]
prev = int(genstr)

Then we use a while loop to run a block of code until length of genstr in less than length s.

while len(genstr) < len(s):

Inside the while loop we declare a variable next and assign prev+1 to it. Subsequently we append genstr with str(next).

while len(genstr) < len(s):
next = prev+1
genstr+=str(next)

Following that we assign the value of next to prev in the while loop

while len(genstr) < len(s):
next = prev+1
genstr+=str(next)
prev = next

With the help of value of i in the for loop, we make the first number to a possible beautiful string and assign it to genstr, Subsequently we append successive numbers to genstr in the while loop using variables prev and next.

Then after the completion of while loop, we compare genstr and s, if genstr is equal to s, then s is a beautiful string and we print “YES” and s[:i], where s[:i] is the first number of the increasing sequence.

if genstr == s:
print("YES", s[:i])
return

Once we exit the for loop upon the exhaustion of values of i, then it’s for sure that s is not a beautiful string and we print “NO”

print("NO")

--

--

Shounak Lohokare

pretending to teach is one of the best way to learn.