Skip to content

Commit 81eb354

Browse files
authored
Create digit-operations-to-make-two-integers-equal.py
1 parent bf0ca49 commit 81eb354

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# Time: O(nlogn)
2+
# Space: O(n)
3+
4+
import heapq
5+
6+
7+
# number theory, dijkstra's algorithm
8+
class Solution(object):
9+
def minOperations(self, n, m):
10+
"""
11+
:type n: int
12+
:type m: int
13+
:rtype: int
14+
"""
15+
def linear_sieve_of_eratosthenes(n): # Time: O(n), Space: O(n)
16+
primes = []
17+
spf = [-1]*(n+1) # the smallest prime factor
18+
for i in xrange(2, n+1):
19+
if spf[i] == -1:
20+
spf[i] = i
21+
primes.append(i)
22+
for p in primes:
23+
if i*p > n or p > spf[i]:
24+
break
25+
spf[i*p] = p
26+
return spf
27+
28+
def dijkstra(start, target):
29+
if spf[start] == start:
30+
return -1
31+
lookup = set()
32+
min_heap = [(start, start)]
33+
while min_heap:
34+
curr, i = heapq.heappop(min_heap)
35+
if i in lookup:
36+
continue
37+
lookup.add(i)
38+
if i == target:
39+
return curr
40+
base = 1
41+
while base <= i:
42+
x = i//base
43+
for d in (-1, 1):
44+
if (1 if x <= 9 else 0) <= x%10+d <= 9 and spf[i+d*base] != i+d*base and i+d*base not in lookup:
45+
heapq.heappush(min_heap, (curr+(i+d*base), i+d*base))
46+
base *= 10
47+
return -1
48+
49+
base = 1
50+
while base < max(n, m):
51+
base *= 10
52+
spf = linear_sieve_of_eratosthenes(base)
53+
return dijkstra(n, m)

0 commit comments

Comments
 (0)