25. Shortest Prime Path
The problem can be found at the following link: Question Link
My Approach
Create a sieve of Eratosthenes to efficiently check for prime numbers.
Initialize a queue for BFS and a set to keep track of visited numbers.
Convert the starting number to a string and enqueue it. Perform BFS, generating all possible variations of the number by changing each digit from 0 to 9.
Check if the generated number is prime and has not been visited before. If true, enqueue and mark as visited.
Continue BFS until the target number is reached.
Time and Auxiliary Space Complexity
Time Complexity:
O(10^4)
, where at max BFS can run for all permutaions which is around (10^4
times).Auxiliary Space Complexity:
O(10^4)
for the visited set and queue.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star to the getlost01/gfg-potd repository.
Last updated