Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App
Next Article:
Probability of reaching a point with 2 or 3 steps at a time
Next article icon

Probability of reaching a point with 2 or 3 steps at a time

Last Updated : 09 Nov, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

A person starts walking from position X = 0, find the probability to reach exactly on X = N if she can only take either 2 steps or 3 steps. Probability for step length 2 is given i.e. P, probability for step length 3 is 1 - P.
Examples : 

Input : N = 5, P = 0.20
Output : 0.32
Explanation :-
There are two ways to reach 5.
2+3 with probability = 0.2 * 0.8 = 0.16
3+2 with probability = 0.8 * 0.2 = 0.16
So, total probability = 0.32.

It is a simple dynamic programming problem. It is simple extension of this problem :- count-ofdifferent-ways-express-n-sum-1-3-4
Below is the implementation of the above approach. 

C++
// CPP Program to find probability to  // reach N with P probability to take // 2 steps (1-P) to take 3 steps #include <bits/stdc++.h> using namespace std;  // Returns probability to reach N float find_prob(int N, float P) {     double dp[N + 1];     dp[0] = 1;     dp[1] = 0;     dp[2] = P;     dp[3] = 1 - P;     for (int i = 4; i <= N; ++i)         dp[i] = (P)*dp[i - 2] + (1 - P) * dp[i - 3];      return dp[N]; }  // Driver code int main() {     int n = 5;     float p = 0.2;     cout << find_prob(n, p);     return 0; } 
Java
// Java Program to find probability to  // reach N with P probability to take // 2 steps (1-P) to take 3 steps import java.io.*;  class GFG {          // Returns probability to reach N     static float find_prob(int N, float P)     {         double dp[] = new double[N + 1];         dp[0] = 1;         dp[1] = 0;         dp[2] = P;         dp[3] = 1 - P;              for (int i = 4; i <= N; ++i)           dp[i] = (P) * dp[i - 2] +                         (1 - P) * dp[i - 3];              return ((float)(dp[N]));     }          // Driver code     public static void main(String args[])     {         int n = 5;         float p = 0.2f;         System.out.printf("%.2f",find_prob(n, p));     } }   /* This code is contributed by Nikita Tiwari.*/ 
Python3
# Python 3 Program to find  # probability to reach N with # P probability to take 2  # steps (1-P) to take 3 steps  # Returns probability to reach N def find_prob(N, P) :          dp =[0] * (n + 1)     dp[0] = 1     dp[1] = 0     dp[2] = P     dp[3] = 1 - P          for i in range(4, N + 1) :         dp[i] = (P) * dp[i - 2] + (1 - P) * dp[i - 3]      return dp[N]  # Driver code n = 5 p = 0.2 print(round(find_prob(n, p), 2))  # This code is contributed by Nikita Tiwari. 
C#
// C# Program to find probability to  // reach N with P probability to take // 2 steps (1-P) to take 3 steps using System;  class GFG {          // Returns probability to reach N     static float find_prob(int N, float P)     {         double []dp = new double[N + 1];         dp[0] = 1;         dp[1] = 0;         dp[2] = P;         dp[3] = 1 - P;              for (int i = 4; i <= N; ++i)         dp[i] = (P) * dp[i - 2] +                 (1 - P) * dp[i - 3];              return ((float)(dp[N]));     }          // Driver code     public static void Main()     {         int n = 5;         float p = 0.2f;         Console.WriteLine(find_prob(n, p));     } }   /* This code is contributed by vt_m.*/ 
JavaScript
<script>  // JavaScript Program to find probability to  // reach N with P probability to take // 2 steps (1-P) to take 3 steps     // Returns probability to reach N     function find_prob(N, P)     {         let dp = [];         dp[0] = 1;         dp[1] = 0;         dp[2] = P;         dp[3] = 1 - P;                for (let i = 4; i <= N; ++i)           dp[i] = (P) * dp[i - 2] +                         (1 - P) * dp[i - 3];                return (dp[N]);     }  // Driver Code         let n = 5;         let p = 0.2;         document.write(find_prob(n, p));              // This code is contributed by chinmoy1997pal. </script> 
PHP
<?php // PHP Program to find probability to  // reach N with P probability to take // 2 steps (1-P) to take 3 steps  // Returns probability to reach N function find_prob($N, $P) {     $dp;     $dp[0] = 1;     $dp[1] = 0;     $dp[2] = $P;     $dp[3] = 1 - $P;     for ($i = 4; $i <= $N; ++$i)         $dp[$i] = ($P) * $dp[$i - 2] +                    (1 - $P) * $dp[$i - 3];      return $dp[$N]; }  // Driver code $n = 5; $p = 0.2; echo find_prob($n, $p);  // This code is contributed by mits. ?> 

Output
0.32

Time Complexity: O(n)
Auxiliary Space: O(n)
 Efficient approach: Space optimization O(1)

In the previous approach, the current value dp[i] only depends on the previous 2 values of dp i.e. dp[i-2] and dp[i-3]. So to optimize the space complexity we can store the previous 4 values of Dp in 4 variables  his way, the space complexity will be reduced from O(N) to O(1)

Implementation Steps:

  • Initialize variables for dp[0], dp[1], dp[2], and dp[3] as 1, 0, P, and 1-P respectively.
  • Iterate from i = 4 to N and use the formula dp[i] = (P)*dp[i - 2] + (1 - P) * dp[i - 3] to compute the current value of dp.
  • After each iteration, update the values of dp0, dp1, dp2, and dp3 to dp1, dp2, dp3, and curr respectively.
  • Return the final value of curr.

Implementation:

C++
// CPP Program to find probability to // reach N with P probability to take // 2 steps (1-P) to take 3 steps #include <bits/stdc++.h> using namespace std;  // Returns probability to reach N float find_prob(int N, float P) {           // to store current value     double curr;            // store previous 4 values of DP      double dp0 = 1, dp1=0, dp2=P, dp3= 1-P;            // iterate over subproblems to get        // current solution from previous computations     for (int i = 4; i <= N; ++i){         curr = (P)*dp2 + (1 - P) * dp1;                  // assigning values to iterate further         dp0=dp1;         dp1=dp2;         dp2=dp3;         dp3=curr;     }            // return final answer     return curr; }  // Driver code int main() {     int n = 5;     float p = 0.2;     cout << find_prob(n, p);     return 0; } 
Java
import java.util.*;  public class Main {      // Returns probability to reach N     static float find_prob(int N, float P) {          // to store current value         double curr;          // store previous 4 values of DP         double dp0 = 1, dp1 = 0, dp2 = P, dp3 = 1 - P;          // iterate over subproblems to get         // current solution from previous computations         for (int i = 4; i <= N; ++i) {             curr = (P) * dp2 + (1 - P) * dp1;              // assigning values to iterate further             dp0 = dp1;             dp1 = dp2;             dp2 = dp3;             dp3 = curr;         }          // return final answer         return (float) curr;     }      // Driver code     public static void main(String[] args) {         int n = 5;         float p = 0.2f;         System.out.println(find_prob(n, p));     } } 
Python3
# Function to find the probability to reach N with P probability to # take 2 steps and (1-P) to take 3 steps def find_prob(N, P):     # Initialize variables to store current and previous values     curr = 0.0      # Initialize previous 4 values of DP     dp0, dp1, dp2, dp3 = 1.0, 0.0, P, 1 - P      # Iterate over subproblems to calculate the      # current solution from previous computations     for i in range(4, N + 1):         curr = P * dp2 + (1 - P) * dp1          # Update values for the next iteration         dp0, dp1, dp2, dp3 = dp1, dp2, dp3, curr      # Round the final answer to 2 decimal places     return round(curr, 2)  # Driver code if __name__ == "__main__":     n = 5     p = 0.2     print(find_prob(n, p)) 
C#
using System;  class Program {     // Function to find the probability to reach N with P probability to take 2 steps and (1-P) to take 3 steps     static double FindProbability(int N, double P)     {         double curr = 0.0;          double dp1 = 0.0, dp2 = P, dp3 = 1 - P;          // Iterate over subproblems to calculate the current solution from previous computations         for (int i = 4; i <= N; i++)         {             curr = P * dp2 + (1 - P) * dp1;              // Update values for the next iteration             dp1 = dp2;             dp2 = dp3;             dp3 = curr;         }          // Return the final answer         return curr;     }      static void Main()     {         int n = 5;         double p = 0.2;         Console.WriteLine(FindProbability(n, p));     } } 
JavaScript
// Returns probability to reach N function find_prob(N, P) {       // to store current value   let curr;      // store previous 4 values of DP    let dp0 = 1, dp1 = 0, dp2 = P, dp3 = 1 - P;      // iterate over subproblems to get    // current solution from previous computations   for (let i = 4; i <= N; ++i) {     curr = (P * dp2) + ((1 - P) * dp1);          // assigning values to iterate further     dp0 = dp1;     dp1 = dp2;     dp2 = dp3;     dp3 = curr;   }      // return final answer   return curr; }  // Driver code let n = 5; let p = 0.2; console.log(find_prob(n, p).toFixed(2)); 

Output
0.32

Time complexity: O(N)
Auxiliary Space: O(1)


Next Article
Probability of reaching a point with 2 or 3 steps at a time

S

Sakshi_Tiwari
Improve
Article Tags :
  • Misc
  • Dynamic Programming
  • Mathematical
  • DSA
  • Probability
Practice Tags :
  • Dynamic Programming
  • Mathematical
  • Misc

Similar Reads

    Find the probability of reaching all points after N moves from point N
    Given N which denotes the initial position of the person on the number line. Also given L which is the probability of the person of going left. Find the probability of reaching all points on the number line after N moves from point N. Each move can be either to the left or to the right. Examples: In
    14 min read
    Finding the probability of a state at a given time in a Markov chain | Set 2
    Given a Markov chain G, we have the find the probability of reaching the state F at time t = T if we start from state S at time t = 0.A Markov chain is a random process consisting of various states and the probabilities of moving from one state to another. We can represent it using a directed graph
    11 min read
    Print all ways to reach the Nth stair with the jump of 1 or 2 units at a time
    Given a positive integer N representing N stairs and a person it at the first stair, the task is to print all ways to reach the Nth stair with the jump of 1 or 2 units at a time. Examples: Input: N = 3Output: 112Explanation:Nth stairs can be reached in the following ways with the jumps of 1 or 2 uni
    6 min read
    Probability of Knight to remain in the chessboard
    Given a n*n chessboard and the knight position (x, y), each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there. The knight continues moving until it has made exactly k moves or has moved off the chess
    15+ min read
    Probability of cutting a rope into three pieces such that the sides form a triangle
    Given a rope. We have to find the probability of cutting a rope into 3 pieces such that they form a triangle. Answer: 0.25 Explanation: Let the length of rope be 1 unit. We choose two points X and Y on the rope. Note: Formation of triangle is based on Triangle inequality i.e. sum of the lengths of a
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences