LeetCode 3377: Digit Operations to Make Two Integers Equal Solution
Master LeetCode problem 3377 (Digit Operations to Make Two Integers Equal), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
3377. Digit Operations to Make Two Integers Equal
Problem Explanation
Explanation
To solve this problem, we can use a breadth-first search (BFS) approach. We start with the initial number n and keep track of the visited numbers to avoid revisiting them. We generate all possible transformations from n by incrementing or decrementing each digit (except 0 and 9) and check if the resulting number is not prime. We continue this process until we reach the target number m or exhaust all possibilities. Finally, we return the minimum cost if m is reachable; otherwise, we return -1.
- Time complexity: O(10^d) where d is the number of digits in the input number
- Space complexity: O(10^d) for storing visited numbers
Solution Code
import java.util.*;
class Solution {
public int minCost(int n, int m) {
Queue<Integer> queue = new LinkedList<>();
Set<Integer> visited = new HashSet<>();
queue.add(n);
visited.add(n);
int cost = 0;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
int curr = queue.poll();
if (curr == m) {
return cost;
}
for (int j = 0; j < String.valueOf(curr).length(); j++) {
int digit = Character.getNumericValue(String.valueOf(curr).charAt(j));
if (digit > 0) {
int nextNum = curr - (int) Math.pow(10, String.valueOf(curr).length() - j - 1);
if (!visited.contains(nextNum) && !isPrime(nextNum)) {
queue.add(nextNum);
visited.add(nextNum);
}
}
if (digit < 9) {
int nextNum = curr + (int) Math.pow(10, String.valueOf(curr).length() - j - 1);
if (!visited.contains(nextNum) && !isPrime(nextNum)) {
queue.add(nextNum);
visited.add(nextNum);
}
}
}
}
cost++;
}
return -1;
}
private boolean isPrime(int num) {
if (num <= 1) return false;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3377 (Digit Operations to Make Two Integers Equal)?
This page provides optimized solutions for LeetCode problem 3377 (Digit Operations to Make Two Integers Equal) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 3377 (Digit Operations to Make Two Integers Equal)?
The time complexity for LeetCode 3377 (Digit Operations to Make Two Integers Equal) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3377 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3377 in Java, C++, or Python.