I received this interview question and got stuck on it:
There are an infinite number of train stops starting from station number 0.
There are an infinite number of trains. The nth train stops at all of the k * 2^(n - 1) stops where k is between 0 and infinity.
When n = 1, the first train stops at stops 0, 1, 2, 3, 4, 5, 6, etc.
When n = 2, the second train stops at stops 0, 2, 4, 6, 8, etc.
When n = 3, the third train stops at stops 0, 4, 8, 12, etc.
Given a start station number and end station number, return the minimum number of stops between them. You can use any of the trains to get from one stop to another stop.
For example, the minimum number of stops between start = 1 and end = 4 is 3 because we can get from 1 to 2 to 4.
I'm thinking about a dynamic programming solution that would store in dp[start][end]
the minimum number of steps between start
and end
. We'd build up the array using start...mid1, mid1...mid2, mid2...mid3, ..., midn...end
. But I wasn't able to get it to work. How do you solve this?
Clarifications:
- Trains can only move forward from a lower number stop to a higher number stop.
- A train can start at any station where it makes a stop at.
- Trains can be boarded in any order. The n = 1 train can be boarded before or after boarding the n = 3 train.
- Trains can be boarded multiple times. For example, it is permitted to board the n = 1 train, next board the n = 2 train, and finally board the n = 1 train again.