VOOZH about

URL: https://www.geeksforgeeks.org/dsa/friends-pairing-problem/

⇱ Friends Pairing Problem - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Friends Pairing Problem

Last Updated : 12 Dec, 2022

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: 

Input : n = 3
Output : 4
Explanation:
{1}, {2}, {3} : all single
{1}, {2, 3} : 2 and 3 paired but 1 is single.
{1, 2}, {3} : 1 and 2 are paired but 3 is single.
{1, 3}, {2} : 1 and 3 are paired but 2 is single.
Note that {1, 2} and {2, 1} are considered same.

Mathematical Explanation:
The problem is simplified version of how many ways we can divide n elements into multiple groups.
(here group size will be max of 2 elements).
In case of n = 3, we have only 2 ways to make a group: 
 1) all elements are individual(1,1,1)
 2) a pair and individual (2,1)
In case of n = 4, we have 3 ways to form a group:
 1) all elements are individual (1,1,1,1)
 2) 2 individuals and one pair (2,1,1)
 3) 2 separate pairs (2,2)
Recommended Practice

For n-th person there are two choices:1) n-th person remains single, we recur for f(n - 1)2) n-th person pairs up with any of the remaining n - 1 persons. We get (n - 1) * f(n - 2)Therefore we can recursively write f(n) as:f(n) = f(n - 1) + (n - 1) * f(n - 2)

Since the above recursive formula has overlapping subproblems, we can solve it using Dynamic Programming.  


Output
10

Time Complexity : O(n) 
Auxiliary Space : O(n)

Another approach: (Using recursion)  


Output
10

Time Complexity : O(n) 
Auxiliary Space : O(n)

Since the above formula is similar to fibonacci number, we can optimize the space with an iterative solution.  


Output
10

Time Complexity : O(n) 
Auxiliary Space : O(1)

Another Approach: Since we can solve the above problem using maths, the solution below is done without using dynamic programming.


Output
10

Time Complexity:  O(n) 
Auxiliary Space: O(n)

Comment
Article Tags: