Approach
Breadth-first search
For Digit Operations to Make Two Integers Equal, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 60 lines of Java from the credited upstream file 3377.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup, work queue.
- 4 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int minOperations(int n, int m) {3 final int MAX = 10000;4 boolean[] isPrime = sieveEratosthenes(MAX);5 if (isPrime[n] || isPrime[m])6 return -1;7 return dijkstra(n, m, isPrime);8 }9 10 private int dijkstra(int src, int dst, boolean[] isPrime) {11 Set<Integer> seen = new HashSet<>(Arrays.asList(src));12 13 Queue<Pair<Integer, Integer>> minHeap =14 new PriorityQueue<>(Comparator.comparingInt(Pair::getKey));15 minHeap.offer(new Pair<>(src, src));16 17 while (!minHeap.isEmpty()) {18 final int cost = minHeap.peek().getKey();19 final int curr = minHeap.poll().getValue();20 if (curr == dst)21 return cost;22 final String s = Integer.toString(curr);23 for (int i = 0; i < s.length(); ++i) {24 char[] chars = s.toCharArray();25 if (chars[i] < '9') {26 ++chars[i];27 final int next = Integer.parseInt(new String(chars));28 if (!isPrime[next] && !seen.contains(next)) {29 minHeap.offer(new Pair<>(cost + next, next));30 seen.add(next);31 }32 --chars[i];33 }34 if (chars[i] > '0' && !(i == 0 && chars[i] == '1')) {35 --chars[i];36 final int next = Integer.parseInt(new String(chars));37 if (!isPrime[next] && !seen.contains(next)) {38 minHeap.offer(new Pair<>(cost + next, next));39 seen.add(next);40 }41 }42 }43 }44 45 return -1;46 }47 48 private boolean[] sieveEratosthenes(int n) {49 boolean[] isPrime = new boolean[n];50 Arrays.fill(isPrime, true);51 isPrime[0] = false;52 isPrime[1] = false;53 for (int i = 2; i * i < n; ++i)54 if (isPrime[i])55 for (int j = i * i; j < n; j += i)56 isPrime[j] = false;57 return isPrime;58 }59}60