Given an integer N, representing the number of stations lying between the source and the destination. There are three trains available from every station and their stoppage patterns are as follows:
- Train 1: Stops at every station
- Train 2: Stops at every alternate station
- Train 3: Stops at every third station
The task is to find the number of ways to reach the destination from the source using any possible combination of trains.
Input: N = 2
Four possible ways exists to travel from source to destination with 2 stations in between:
Train 1 (from source) -> Train 1 (from station 1) -> Train 1(from station 2) -> Destination
Train 2 (from source) -> Train 1 (from station 2) -> Destination
Train 1 (from source) -> Train 2 (from station 1) -> Destination
Train 3 (from source) -> Destination
Input: N = 0
Explanation: No station is present in between the source and destination. Therefore, there is only one way to travel, i.e.
Train 1(from source) -> Destination
F(N) = F(N – 1) + F(N – 2) + F(N – 3),
F(N – 1) counts ways to travel upto (N – 1)th station.
F(N – 2) counts ways to travel upto (N – 2)th station.
F(N – 3) counts ways to travel upto (N – 3)th station.
Follow the steps below to solve the problem:
- Initialize an array dp for memorization. Set all indices to -1 initially.
- Define a recursive function findWays() to calculate the number of ways to reach the Nth station.
- Following base cases are required to be considered:
- For x < 0 return 0.
- For x = 0, return 1.
- For x = 1, return 2.
- For x = 2, return 4.
- If the current state, say x, is already evaluated i.e. dp[x] is not equal to -1, simply return the evaluated value.
- Otherwise, calculate findWays(x – 1), findWays(x – 2) and findWays(x – 3) recursively and store their sum in dp[x].
- Return dp[x].
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.