Count number of ways to cover a distance
Last Updated :
24 May, 2024
Given a distance ‘dist’, count total number of ways to cover the distance with 1, 2 and 3 steps.
Examples:
Input: n = 3
Output: 4
Explanation: Below are the four ways
=> 1 step + 1 step + 1 step
=> 1 step + 2 step
=> 2 step + 1 step
=> 3 step
Input: n = 4
Output: 7
Explanation: Below are the four ways
=> 1 step + 1 step + 1 step + 1 step
=> 1 step + 2 step + 1 step
=> 2 step + 1 step + 1 step
=> 1 step + 1 step + 2 step
=> 2 step + 2 step
=> 3 step + 1 step
=> 1 step + 3 step
Count number of ways to cover a distance using Recursion:
There are n stairs, and a person is allowed to next step, skip one position or skip two positions. So there are n positions. The idea is standing at the ith position the person can move by i+1, i+2, i+3 position. So a recursive function can be formed where at current index i the function is recursively called for i+1, i+2 and i+3 positions.
There is another way of forming the recursive function. To reach position i, a person has to jump either from i-1, i-2 or i-3 position where i is the starting position.
Step by step approach:
- Create a recursive function (count(int n)) which takes only one parameter.
- Check the base cases. If the value of n is less than 0 then return 0, and if value of n is equal to zero then return 1 as it is the starting position.
- Call the function recursively with values n-1, n-2 and n-3 and sum up the values that are returned, i.e. sum = count(n-1) + count(n-2) + count(n-3).
- Return the value of sum.
Below are the implementation of the above approach:
C++
// A naive recursive C++ program to count number of ways to
// cover a distance with 1, 2 and 3 steps
#include <iostream>
using namespace std;
// Returns count of ways to cover 'dist'
int printCountRec(int dist)
{
// Base cases
if (dist < 0)
return 0;
if (dist == 0)
return 1;
// Recur for all previous 3 and add the results
return printCountRec(dist - 1) + printCountRec(dist - 2)
+ printCountRec(dist - 3);
}
// driver program
int main()
{
int dist = 4;
cout << printCountRec(dist);
return 0;
}
Java
// A naive recursive Java program to count number
// of ways to cover a distance with 1, 2 and 3 steps
import java.io.*;
class GFG
{
// Function returns count of ways to cover 'dist'
static int printCountRec(int dist)
{
// Base cases
if (dist<0)
return 0;
if (dist==0)
return 1;
// Recur for all previous 3 and add the results
return printCountRec(dist-1) +
printCountRec(dist-2) +
printCountRec(dist-3);
}
// driver program
public static void main (String[] args)
{
int dist = 4;
System.out.println(printCountRec(dist));
}
}
// This code is contributed by Pramod Kumar
Python
# A naive recursive Python3 program
# to count number of ways to cover
# a distance with 1, 2 and 3 steps
# Returns count of ways to
# cover 'dist'
def printCountRec(dist):
# Base cases
if dist < 0:
return 0
if dist == 0:
return 1
# Recur for all previous 3 and
# add the results
return (printCountRec(dist-1) +
printCountRec(dist-2) +
printCountRec(dist-3))
# Driver code
dist = 4
print(printCountRec(dist))
# This code is contributed by Anant Agarwal.
C#
// A naive recursive C# program to
// count number of ways to cover a
// distance with 1, 2 and 3 steps
using System;
class GFG {
// Function returns count of
// ways to cover 'dist'
static int printCountRec(int dist)
{
// Base cases
if (dist < 0)
return 0;
if (dist == 0)
return 1;
// Recur for all previous 3
// and add the results
return printCountRec(dist - 1) +
printCountRec(dist - 2) +
printCountRec(dist - 3);
}
// Driver Code
public static void Main ()
{
int dist = 4;
Console.WriteLine(printCountRec(dist));
}
}
// This code is contributed by Sam007.
JavaScript
// A naive recursive javascript program to count number of ways to cover
// a distance with 1, 2 and 3 steps
// Returns count of ways to cover 'dist'
function printCountRec(dist)
{
// Base cases
if (dist<0) return 0;
if (dist==0) return 1;
// Recur for all previous 3 and add the results
return printCountRec(dist-1) +
printCountRec(dist-2) +
printCountRec(dist-3);
}
// driver program
var dist = 4;
console.log(printCountRec(dist));
Time Complexity: O(3n), the time complexity of the above solution is exponential, a close upper bound is O(3n). From each state 3, a recursive function is called. So the upper bound for n states is O(3n).
Auxiliary Space: O(1), No extra space is required.
The problem have overlapping subproblems, meaning that the same subproblems are encountered multiple times during the recursive computation. For example, when calculating the number of ways to cover distance ‘dist’, we need to calculate the number of ways to cover distances ‘dist-1’, ‘dist-2’, and ‘dist-3’. These subproblems are also encountered when calculating the number of ways to cover distances ‘dist-2’ and ‘dist-3’.
Memoization solve this issue by storing the results of previously computed subproblems in a data structure, typically an array or a hash table.
Before making a recursive call, we first check if the result for the current distance has already been computed and stored in the memo[] array. If it has, we directly return the stored result, avoiding the recursive call. This significantly reduces the number of recursive calls and improves the performance of the algorithm, especially for larger distances. Once the result for the current distance is computed, we store it in the memo[] array for future reference.
Below is the implementation of the above approach:
C++
#include <iostream>
#include <vector>
using namespace std;
// Returns count of ways to cover 'dist' using memoization
int printCountRecMemo(int dist, vector<int>& memo)
{
// Base cases
if (dist < 0)
return 0;
if (dist == 0)
return 1;
// Check if the value for 'dist' is already computed
if (memo[dist] != -1)
return memo[dist];
// Recur for all previous 3 and add the results
int ways = printCountRecMemo(dist - 1, memo)
+ printCountRecMemo(dist - 2, memo)
+ printCountRecMemo(dist - 3, memo);
// Memoize the result for 'dist' for future use
memo[dist] = ways;
return ways;
}
// Function to calculate the count of ways with memoization
int countWays(int dist)
{
vector<int> memo(
dist + 1,
-1); // Initialize memoization array with -1
return printCountRecMemo(dist, memo);
}
// Driver program
int main()
{
int dist = 4;
cout << countWays(dist);
return 0;
}
Java
import java.util.Arrays;
public class Main {
// Function to calculate the count of ways with memoization
static int countWays(int dist) {
int[] memo = new int[dist + 1]; // Initialize memoization array with 0s
Arrays.fill(memo, -1); // Set all elements to -1 to indicate not computed yet
return printCountRecMemo(dist, memo);
}
// Recursive function to calculate the count of ways to cover 'dist' using memoization
static int printCountRecMemo(int dist, int[] memo) {
// Base cases
if (dist < 0)
return 0;
if (dist == 0)
return 1;
// Check if the value for 'dist' is already computed
if (memo[dist] != -1)
return memo[dist];
// Recur for all previous 3 and add the results
int ways = printCountRecMemo(dist - 1, memo)
+ printCountRecMemo(dist - 2, memo)
+ printCountRecMemo(dist - 3, memo);
// Memoize the result for 'dist' for future use
memo[dist] = ways;
return ways;
}
// Driver program
public static void main(String[] args) {
int dist = 4;
System.out.println(countWays(dist));
}
}
Python
# Function to calculate the count of ways to cover 'dist' using memoization
def printCountRecMemo(dist, memo):
# Base cases
if dist < 0:
return 0
if dist == 0:
return 1
# Check if the value for 'dist' is already computed
if memo[dist] != -1:
return memo[dist]
# Recur for all previous 3 and add the results
ways = printCountRecMemo(dist - 1, memo) \
+ printCountRecMemo(dist - 2, memo) \
+ printCountRecMemo(dist - 3, memo)
# Memoize the result for 'dist' for future use
memo[dist] = ways
return ways
# Function to calculate the count of ways with memoization
def countWays(dist):
memo = [-1] * (dist + 1) # Initialize memoization list with -1
return printCountRecMemo(dist, memo)
# Driver program
if __name__ == "__main__":
dist = 4
print(countWays(dist))
JavaScript
// Function to calculate the count of ways with memoization
function countWays(dist) {
let memo = new Array(dist + 1).fill(-1); // Initialize memoization array with -1s
// Recursive function to calculate the count of ways to cover 'dist' using memoization
function printCountRecMemo(dist, memo) {
// Base cases
if (dist < 0)
return 0;
if (dist === 0)
return 1;
// Check if the value for 'dist' is already computed
if (memo[dist] !== -1)
return memo[dist];
// Recur for all previous 3 and add the results
let ways = printCountRecMemo(dist - 1, memo)
+ printCountRecMemo(dist - 2, memo)
+ printCountRecMemo(dist - 3, memo);
// Memoize the result for 'dist' for future use
memo[dist] = ways;
return ways;
}
// Call recursive function with memoization
return printCountRecMemo(dist, memo);
}
// Driver program
let dist = 4;
console.log(countWays(dist));
Time Complexity: O(n)
Auxiliary Space: O(n)
We start by initializing the base cases for covering distances 0, 1, and 2. For distance 0, there is only one way to cover it (do nothing). For distance 1, there is also only one way to cover it (take a step of size 1). For distance 2, there are two ways to cover it (take two steps of size 1 or take a step of size 2).
We use a bottom-up approach to fill in the count[] array. For each entry count[i], we compute the number of ways to cover distance i by adding the number of ways to cover distances i-1, i-2, and i-3.
Finally, we return the value of count[dist], which represents the number of ways to cover the given distance.
Below is the implementation of the above approach:
C++
// A Dynamic Programming based C++ program to count number of ways
// to cover a distance with 1, 2 and 3 steps
#include<iostream>
using namespace std;
int printCountDP(int dist)
{
int count[dist+1];
// Initialize base values. There is one way to cover 0 and 1
// distances and two ways to cover 2 distance
count[0] = 1;
if(dist >= 1)
count[1] = 1;
if(dist >= 2)
count[2] = 2;
// Fill the count array in bottom up manner
for (int i=3; i<=dist; i++)
count[i] = count[i-1] + count[i-2] + count[i-3];
return count[dist];
}
// driver program
int main()
{
int dist = 4;
cout << printCountDP(dist);
return 0;
}
Java
// A Dynamic Programming based Java program
// to count number of ways to cover a distance
// with 1, 2 and 3 steps
import java.io.*;
class GFG
{
// Function returns count of ways to cover 'dist'
static int printCountDP(int dist)
{
int[] count = new int[dist+1];
// Initialize base values. There is one way to
// cover 0 and 1 distances and two ways to
// cover 2 distance
count[0] = 1;
if(dist >= 1)
count[1] = 1;
if(dist >= 2)
count[2] = 2;
// Fill the count array in bottom up manner
for (int i=3; i<=dist; i++)
count[i] = count[i-1] + count[i-2] + count[i-3];
return count[dist];
}
// driver program
public static void main (String[] args)
{
int dist = 4;
System.out.println(printCountDP(dist));
}
}
// This code is contributed by Pramod Kumar
Python
# A Dynamic Programming based on Python3
# program to count number of ways to
# cover a distance with 1, 2 and 3 steps
def printCountDP(dist):
count = [0] * (dist + 1)
# Initialize base values. There is
# one way to cover 0 and 1 distances
# and two ways to cover 2 distance
count[0] = 1
if dist >= 1 :
count[1] = 1
if dist >= 2 :
count[2] = 2
# Fill the count array in bottom
# up manner
for i in range(3, dist + 1):
count[i] = (count[i-1] +
count[i-2] + count[i-3])
return count[dist];
# driver program
dist = 4;
print( printCountDP(dist))
# This code is contributed by Sam007.
C#
// A Dynamic Programming based C# program
// to count number of ways to cover a distance
// with 1, 2 and 3 steps
using System;
class GFG {
// Function returns count of ways
// to cover 'dist'
static int printCountDP(int dist)
{
int[] count = new int[dist + 1];
// Initialize base values. There is one
// way to cover 0 and 1 distances
// and two ways to cover 2 distance
count[0] = 1;
count[1] = 1;
count[2] = 2;
// Fill the count array
// in bottom up manner
for (int i = 3; i <= dist; i++)
count[i] = count[i - 1] +
count[i - 2] +
count[i - 3];
return count[dist];
}
// Driver Code
public static void Main ()
{
int dist = 4;
Console.WriteLine(printCountDP(dist));
}
}
// This code is contributed by Sam007.
JavaScript
// A Dynamic Programming based Javascript program
// to count number of ways to cover a distance
// with 1, 2 and 3 steps
// Function returns count of ways
// to cover 'dist'
function printCountDP(dist)
{
let count = new Array(dist + 1);
// Initialize base values. There is one
// way to cover 0 and 1 distances
// and two ways to cover 2 distance
count[0] = 1;
if (dist >= 1)
count[1] = 1;
if (dist >= 2)
count[2] = 2;
// Fill the count array
// in bottom up manner
for(let i = 3; i <= dist; i++)
count[i] = count[i - 1] +
count[i - 2] +
count[i - 3];
return count[dist];
}
// Driver code
let dist = 4;
console.log(printCountDP(dist));
// This code is contributed by divyeshrabadiya07
PHP
<?php
// A Dynamic Programming based PHP program
// to count number of ways to cover a
// distance with 1, 2 and 3 steps
function printCountDP( $dist)
{
$count = array();
// Initialize base values. There is
// one way to cover 0 and 1 distances
// and two ways to cover 2 distance
$count[0] = 1; $count[1] = 1;
$count[2] = 2;
// Fill the count array
// in bottom up manner
for ( $i = 3; $i <= $dist; $i++)
$count[$i] = $count[$i - 1] +
$count[$i - 2] +
$count[$i - 3];
return $count[$dist];
}
// Driver Code
$dist = 4;
echo printCountDP($dist);
// This code is contributed by anuj_67.
?>
Time Complexity: O(n), Only one traversal of the array is needed.
Auxiliary Space: O(n), To store the values in a DP O(n) extra space is needed.
Count number of ways to cover a distance using Contant Space O(1):
From the above solution, we can observe that only three previous states are required to compute the value of current state. So, creates an array of size 3, where each element represents the number of ways to reach a certain distance. The base cases are initialized to 1 for distance 0 and 1, and 2 for distance 2. The remaining elements are filled using the recurrence relation, which states that the number of ways to reach a certain distance is the sum of the number of ways to reach the previous three distances. The final answer is the number of ways to reach the given distance, which is stored in the last element of the array.
Below is the implementation of the above approach:
C++
// A Dynamic Programming based C++ program to count number of ways
#include<iostream>
using namespace std;
int printCountDP(int dist)
{
//Create the array of size 3.
int ways[3] , n = dist;
//Initialize the bases cases
ways[0] = 1;
ways[1] = 1;
ways[2] = 2;
//Run a loop from 3 to n
//Bottom up approach to fill the array
for(int i=3 ;i<=n ;i++)
ways[i%3] = ways[(i-1)%3] + ways[(i-2)%3] + ways[(i-3)%3];
return ways[n%3];
}
// driver program
int main()
{
int dist = 4;
cout << printCountDP(dist);
return 0;
}
Java
// A Dynamic Programming based Java program to count number of ways
import java.util.*;
class GFG {
static int printCountDP(int dist)
{
// Create the array of size 3.
int []ways = new int[3];
int n = dist;
// Initialize the bases cases
ways[0] = 1;
ways[1] = 1;
ways[2] = 2;
// Run a loop from 3 to n
// Bottom up approach to fill the array
for(int i=3 ;i<=n ;i++)
ways[i%3] = ways[(i-1)%3] + ways[(i-2)%3] + ways[(i-3)%3];
return ways[n%3];
}
// driver program
public static void main(String arg[])
{
int dist = 4;
System.out.print(printCountDP(dist));
}
}
// this code is contributed by shivanisinghss2110
Python
# A Dynamic Programming based C++ program to count number of ways
def prCountDP( dist):
# Create the array of size 3.
ways = [0]*3
n = dist
# Initialize the bases cases
ways[0] = 1
ways[1] = 1
ways[2] = 2
# Run a loop from 3 to n
# Bottom up approach to fill the array
for i in range(3, n + 1):
ways[i % 3] = ways[(i - 1) % 3] + ways[(i - 2) % 3] + ways[(i - 3) % 3]
return ways[n % 3]
# driver program
dist = 4
print(prCountDP(dist))
# This code is contributed by shivanisinghss2110
C#
// A Dynamic Programming based C#
// program to count number of ways
using System;
class GFG{
static int printCountDP(int dist)
{
// Create the array of size 3.
int []ways = new int[3];
int n = dist;
// Initialize the bases cases
ways[0] = 1;
ways[1] = 1;
ways[2] = 2;
// Run a loop from 3 to n
// Bottom up approach to fill the array
for(int i = 3; i <= n; i++)
ways[i % 3] = ways[(i - 1) % 3] +
ways[(i - 2) % 3] +
ways[(i - 3) % 3];
return ways[n % 3];
}
// Driver code
public static void Main(String []arg)
{
int dist = 4;
Console.Write(printCountDP(dist));
}
}
// This code is contributed by shivanisinghss2110
JavaScript
// A Dynamic Programming based javascript program to count number of ways
function printCountDP( dist)
{
//Create the array of size 3.
var ways= [] , n = dist;
ways.length = 3 ;
//Initialize the bases cases
ways[0] = 1;
ways[1] = 1;
ways[2] = 2;
//Run a loop from 3 to n
//Bottom up approach to fill the array
for(var i=3 ;i<=n ;i++)
ways[i%3] = ways[(i-1)%3] + ways[(i-2)%3] + ways[(i-3)%3];
return ways[n%3];
}
// driver code
var dist = 4;
console.write(printCountDP(dist));
Time Complexity: O(n).
Auxiliary Space: O(1)
Similar Reads
Counting the number of words in a Trie
A Trie is used to store dictionary words so that they can be searched efficiently and prefix search can be done. The task is to write a function to count the number of words. Example : Input : root / \ \ t a b | | | h n y | | \ | e s y e / | | i r w | | | r e e | r Output : 8 Explanation : Words for
7 min read
Convert a tree to forest of even nodes
Given a tree of n even nodes. The task is to find the maximum number of edges to be removed from the given tree to obtain a forest of trees having an even number of nodes. This problem is always solvable as the given graph has even nodes. Examples: Input: Output: 2Explanation: By removing 2 edges sh
8 min read
Count ways to reach the nth stair using step 1, 2 or 3
A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. The task is to implement a method to count how many possible ways the child can run up the stairs. Examples: Input: 4Output: 7Explanation: There are seven ways: {1, 1, 1, 1}, {1, 2, 1}, {2, 1, 1}
15+ min read
Sum of all the Composite Numbers from Odd indices of the given array
Given an array arr[] of size N which contains at least one composite number. The task is to find out the sum of all the composite numbers in the array which are at odd indices (where indexing is 1 based). Examples: Input: arr = [13, 5, 8, 16, 25] Output: 33 Explanation: The number in the odd indices
6 min read
Count of N-bit odd and even integers with K set bits
Given two positive integers N and K, the task is to count the number of even and odd integers consisting of N bits, out of which K bits are set. Examples: Input: N = 5, K = 2Output: 3 1Explanation:The 5 bit even integers having 2 set bits are: 10010(= 18), 10100(= 20), 11000(= 24). So, the count is
6 min read
Program to convert given Matrix to a Diagonal Matrix
Given a N*N matrix. The task is to convert the matrix to a diagonal matrix. That is to change the values of the non-diagonal elements of a matrix to 0.Diagonal-Matrix: A matrix is called a Diagonal Matrix if all the non-diagonal elements of the matrix are zero.Examples: Input : mat[][] = {{ 2, 1, 7
8 min read
HCF of array of fractions (or rational numbers)
Given a fraction series. Find the H.C.F of a given fraction series. Examples: Input : [{2, 5}, {8, 9}, {16, 81}, {10, 27}] Output : 2, 405 Explanation : 2/405 is the largest number that divides all 2/5, 8/9, 16/81 and 10/27. Input : [{9, 10}, {12, 25}, {18, 35}, {21, 40}] Output : 3, 1400 Approach:
8 min read
Count of ways to make sum of all columns 0 by changing any number of 1s in Matrix to -1
Given a matrix of size N x M initially filled with 1, the task is to find the number of ways to make the sum of all columns 0 by changing any number of 1's to -1. Note: As the answer can be very large print it modulo 1e9 + 7 Examples: Input: N = 2, M = 1Output: 2Explanation: Upper example consist 2
6 min read
Minimum cost to convert a string to another by replacing blanks
Given two strings s1 and s2 with lower-case alphabets having length N. The strings s1 and s2 initially may contain some blanks, the task is to find minimum operations to convert a string s1 to s2. Initially, if there are any blanks they should be replaced by any same character which cost 0 andAny vo
9 min read
Count frequency of digit K in given Array
Given an array arr[] of integers of size N and a single digit integer K. The task is to find the total count of occurrences of the digit K in the array Examples: Input: arr[] = {15, 66, 26, 91}, K = 6Output: 3Explanation: Occurrences of 6 in each array elements are: 0, 2, 1, 0 respectively.Therefore
5 min read
Number of subarrays for which product and sum are equal
Given a array of n numbers. We need to count the number of subarrays having the product and sum of elements are equal Examples: Input : arr[] = {1, 3, 2} Output : 4 The subarrays are : [0, 0] sum = 1, product = 1, [1, 1] sum = 3, product = 3, [2, 2] sum = 2, product = 2 and [0, 2] sum = 1+3+2=6, pro
5 min read
Check whether two strings contain same characters in same order
Given two strings s1 and s2, the task is to find whether the two strings contain the same characters that occur in the same order. For example string "Geeks" and string "Geks" contain the same characters in same order. Examples: Input: s1 = "Geeks", s2 = "Geks" Output: Yes Input: s1 = "Arnab", s2 =
9 min read
Minimum moves to make tree nodes non-negative
Given a tree consisting of N nodes where the value of each node is the negative of its node number (i.e., 1st node has a value of -1, 2nd node has a value of -2, and so on) and a parent array Par[] that stores the parent node of the ith node. You can choose any node from the tree and add 1 to all no
7 min read
Rotate Doubly linked list by N nodes
Given a doubly-linked list, the task is to rotate the linked list counter-clockwise by p nodes. Here p is a given positive integer and is smaller than the count of nodes in the linked list. Examples: Input: Output: Explanation: After rotating the list by p = 2, the new head will be the node with val
12 min read
Print all Prime Quadruplet of a number less than it
Given a positive integer n, print every Prime Quadruplet below [Tex]n [/Tex].Prime quadruplet: In mathematics, Prime Quadruplet is a set of four primes of the form {p, p+2, p+6, p+8 }.Example : Input : N = 15 Output : 5 7 11 13 Input : N = 20 Output : 5 7 11 13 11 13 17 19 A Simple solution to gener
7 min read
Amazon Interview Experience | Set 258 (Off-Campus for SDE-1)
I recently had interviews with Amazon at Hyderabad for SDE 1. I had around 1 year and 9 months of experience. Telephonic Interview : It started with a brief introduction of mine and my work. Then he asked me a coding question 1) Given a linked list eg : 1->2->3->4->5->6, make the following changes 1
4 min read
Minimum numbers needed to express every integer below N as a sum
We have an integer N. We need to express N as a sum of K integers such that by adding some(or all) of these integers we can get all the numbers in the range[1, N]. What is the minimum value of K? Examples: Input : N = 7 Output : 3 Explanation : Three integers are 1, 2, 4. By adding some(or all) of t
5 min read
Minimum steps to convert one binary string to other only using negation
Given two binary strings A and B, the task is to convert A to B by choosing any sub-string of A and negating it (replace each 0 with 1 and each 1 with 0). Print the minimum number of operations required. Examples: Input: A = "101010", B = "110011" Output: 2 Choose the sub-string of length 2 from ind
7 min read
Series summation if T(n) is given and n is very large
Given a sequence whose nth term is T(n) = n2 - (n - 1)2 The task is to evaluate the sum of first n terms i.e. S(n) = T(1) + T(2) + T(3) + ... + T(n) Print S(n) mod (109 + 7).Examples: Input: n = 3 Output: 9 S(3) = T(1) + T(2) + T(3) = (12 - 02) + (22 - 12) + (32 - 22) = 1 + 3 + 5 = 9Input: n = 10 Ou
3 min read