Friends Pairing Problem
Pattern: 1D DP
Each friend stays single or pairs with one other friend. For n friends, friend n either stays single (f(n - 1) ways for the rest) or pairs with one of the other n - 1 friends (f(n - 2) ways each).
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
Each of n friends may stay single or pair up with exactly one other friend. Return the number of ways. The answer is taken modulo 10⁹ + 7.
n = 3 gives 4. The catalogue has no practice link for this one.
Think first
- What can the last friend do?
- If they pair up, with how many choices?
- What is left after pairing?
Hints
Brute force, and why it fails
List every pairing: exponential.
The key insight
Fixing what the last friend does splits all pairings into two groups counted by smaller cases.
Dry run
| f | 1 2 |
|---|
f(1) = 1, f(2) = 2.
Step 1 of 2
The plan
f(0) = f(1) = 1
f(n) = f(n - 1) + (n - 1) × f(n - 2)
Complexity
- Time
O(n)- Space
O(1)
Two values carried.
Edge cases
- n = 1: 1.
- n = 2: 2.
- Large n: modulo.
I've built my logic, show the code
Java
class Solution {
public int countFriendsPairings(int n) {
final long MOD = 1_000_000_007L;
long a = 1, b = 1; // ways for i - 2 and i - 1 friends
for (int i = 2; i <= n; i++) {
long c = (b + (long) (i - 1) * a) % MOD; // friend i stays single, or pairs with one of the other i - 1
a = b;
b = c;
}
return (int) b;
}
}C++
class Solution {
public:
int countFriendsPairings(int n) {
const long long MOD = 1000000007LL;
long long a = 1, b = 1; // ways for i - 2 and i - 1 friends
for (int i = 2; i <= n; i++) {
long long c = (b + static_cast<long long>(i - 1) * a) % MOD; // single, or paired with one of i - 1
a = b;
b = c;
}
return static_cast<int>(b);
}
};Python
class Solution:
def countFriendsPairings(self, n: int) -> int:
MOD = 1_000_000_007
a = b = 1 # ways for i - 2 and i - 1 friends
for i in range(2, n + 1):
a, b = b, (b + (i - 1) * a) % MOD # friend i stays single, or pairs with one of the other i - 1
return bCommon mistakes
- Forgetting the (n - 1) factor.
- Overflow.