I was asked in an interview to code the following scenario
A tv has 0-450 channels but the remote buttons 2,5,8,9 have malfunctioned so write a program to get input from the user and traverse that channel through the shortest path
EXAMPLE:
47 -> no need to traverse button 4,7 is available
45 -> 44+1 output from which channel to traverse and how many traversal required to reach 45.
55 -> 55 can be reached from 47 only coz 54 has 5. |||ly (50-55) has 5 in it so again 48 and 49 has 8 and 9 respectively.
I've tried my logic but not even able to code in such a way it is best shortest path for all input PLEASE help me with the logic or show me the program.
Shortest path algorithms are a family of algorithms used for solving the shortest path problem. It is a shortest path problem where the shortest path between a given pair of vertices is computed. A* Search Algorithm is a famous algorithm used for solving single-pair shortest path problem.
As we saw above, transporation problems (with solutions like Google Maps, Waze, and countless others) are a prime example of real-world applications for shortest path problems. There are a few others to consider as well if you aren’t convinced yet. Have you ever used a flip book to animate a scene?
It is a shortest path problem where the shortest path between every pair of vertices is computed. Floyd-Warshall Algorithm and Johnson’s Algorithm are the famous algorithms used for solving All pairs shortest path problem. Get more notes and other study material of Design and Analysis of Algorithms.
However, for computer scientists this problem takes a different turn, as different algorithms may be needed to solve the different problems. For simplicity, shortest path algorithms operate on a graph, which is made up of vertices and edges that connect them.
Think in another way. A valid solution can only be formed by valid digits.
0,1,3,4,6,7
Generate two numbers nearest to the channel number on both side with valid button set only.
For example: channel number = 189
Blind all digits on the right of first invalid digit -> 18x
Upper bound: Look for a slightly bigger digit of 8 from valid set, but not found. In such case, we look for a bigger valid digit of 1, we get 3. Then pad smallest valid digit for the rest. We get 300.
Lower bound: Look for a slightly smaller digit of 8 from valid set, we get 7. Then pad largest valid digit for the rest. We get 177.
Consider boundary case if lower or upper bound cannot be formed (channel number 450 should get 0 as valid solution) and out of upper limit
Compare the two numbers with the channel number and obtain the closest one.
Format and Output
Time complexity: O(log(n)) for all cases
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With