Skip to main content

Coding Problems : Hacker Rank (Separate The Numbers)

 Here I found one interesting question from Hacker Rank, So Let's dig into question and write code....

Question you can see Here

Note: Read the question and try to understand and solve it.

Here we'll see two different ways to solve it..

Method 1:

  • Iterative Method:

# for ex. s = "91011"
def separateNumbers(s):
res = 'NO'
for i in range(len(s)):
#i = 0 , starting digit = 9
starting_digit = int(s[ : i + 1])
new_s = str(starting_digit)

#len(new_s) = 1 , len(s)=8 ,not same
if len(new_s) != len(s):
digit = starting_digit
while len(new_s) < len(s):
# digit = 9
digit += 1 # digit = 10
new_s += str(digit) # new_s = "910" (10 concatenet)
# loop break when len(new_s) >= len(s)
# after loop breaks new_s = "91011"
if new_s == s:
res = f"YES {starting_digit}"
break
print(res)

Method 2:

  • Recursive Method: 
 
import re
def separateNumbers(s):
for i in range(0, len(s)//2):
if checkComply(s[0:i+1], s[i+1:]):
print(f'YES {s[0:i+1]}')
return
print('NO')
# for checking if there are two continues number's difference is = 1
def checkComply(p1, p2):
# next expected number = next_num
next_num = str(int(p1) + 1)
# match patter with p2
match = re.match(next_num, p2)
if match:
# replace next_num in p2 with ""(only first occurence)
p2_new = p2.replace(next_num, '', 1)
# recursion till len(p2_new == 0)or match == None
if len(p2_new) == 0:
return True
return checkComply(next_num, p2_new)
else:
return False

Note: If You've any other solution then share with us in comment box.

Thank You 😊😊

GitHub



Other Important Post

 

Comments

Popular posts from this blog

Makefile

 You may have seen file named Makefile or you may have type command like make, make install. so what is this file Makefile and what are this command. let's discuss about it.

Products Which I like

Induction Buy now Induction Buy now

Pascal's Triangle

 Pascal's Triangle Introduction In mathematics, Pascal’s triangle is triangular array of binomial coefficient. below you can see how it looks like… 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 How to Build it? First of all start with “1” and second rows as “1 1” then we can clearly see every element in next rows(except 1) if sum of two elements from above row. (i.e, 1+1=2, 1+2=3, 1+3=4) and with this rules we can create pascal’s triangle of n rows. Below is visual of how it will look like, Formula let’s take 0th row as first row and 0th column as first column, so we can get each value using formula where n is row number and k is column number. so for finding 1st(0 indexed) element in 2nd row we can write 2C1 which will give 2. There is one another technique, in which we need to solve (x + y)^n for nth row, if we solve (x +y)² then we will get 2nd row as coefficient of x and y in this solved formula which is x² + 2xy + y² . coefficients are (...