We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
def downToZero(n):
if n == 0:
return 0
queue = deque([(n, 0)])
visited = set([n])
while queue:
current, moves = queue.popleft()
if current == 0:
return moves
# Operation 1
if current - 1 not in visited:
queue.append((current - 1, moves + 1))
visited.add(current - 1)
# Operation 2
for i in range(2, int(current**0.5) + 1):
if current % i == 0:
factor = max(i, current // i)
if factor not in visited:
queue.append((factor, moves + 1))
visited.add(factor)
return -1
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
An unexpected error occurred. Please try reloading the page. If problem persists, please contact support@hackerrank.com
Down to Zero II
You are viewing a single comment's thread. Return to all comments →
def downToZero(n): if n == 0: return 0 queue = deque([(n, 0)]) visited = set([n])