FAANG Interview Preparation

Friends Pairing Problem

Given N friends, each one can remain single or can be paired up with some other friend. Each friend can be paired only once. Find out the total number of ways in which friends can remain single or can be paired up.

Examples-

image

Recursive Algorithm

f(n) = ways n people can remain single 
       or pair up.

For n-th person there are two choices:
1) n-th person remains single, so only 1 way so  we recur 
   for remaining i.e f(n - 1)   or you can say 1*f(n-1)
2) n-th person pairs up with any of the 
   remaining n - 1 persons. So apart from the 2 people forming a pair for remaining n-2 persons we We get (n - 1) * f(n - 2) ways

Therefore we can recursively write f(n) as:
f(n) = f(n - 1) + (n - 1) * f(n - 2)

Recursive Code

int countFriendsPairings(int n) 
    { 
        if(n<=2) 
            return n;
        return countFriendsPairings(n-1)+ (n-1)*countFriendsPairings(n-2);
    }

This code gives TLE. It has overlapping suproblems :(
So use Dynamic Programming

int countFriendsPairings(int n) 
    { 
         int m=1e9+7;
         long long int dp[n+1];
         dp[0]=1;
         dp[1]=1;
         for (long long int i = 2; i <= n; i++) 
         {
                dp[i] = ((dp[i - 1]%m) + (((i - 1) * dp[i - 2])%m))%m;
         }
         return dp[n];
    }
Comments (0)