Direction Assignments with Exactly K Visible People Problem
Description
LeetCode Problem 3881.
You are given three integers n, pos, and k.
There are n people standing in a line indexed from 0 to n - 1. Each person independently chooses a direction:
'L': visible only to people on their right'R': visible only to people on their left
A person at index pos sees others as follows:
- A person
i < posis visible if and only if they choose'L'. - A person
i > posis visible if and only if they choose'R'.
Return the number of possible direction assignments such that the person at index pos sees exactly k people.
Since the answer may be large, return it modulo 10^9 + 7.
Example 1:
Input: n = 3, pos = 1, k = 0
Output: 2
Explanation:
- Index 0 is to the left of pos = 1, and index 2 is to the right of pos = 1.
- To see k = 0 people, index 0 must choose 'R' and index 2 must choose 'L', keeping both invisible.
- The person at index 1 can choose 'L' or 'R' since it does not affect the count. Thus, the answer is 2.
Example 2:
Input: n = 3, pos = 2, k = 1
Output: 4
Explanation:
- Index 0 and index 1 are left of pos = 2, and there is no index to the right.
- To see k = 1 person, exactly one of index 0 or index 1 must choose 'L', and the other must choose 'R'.
- There are 2 ways to choose which index is visible from the left.
- The person at index 2 can choose 'L' or 'R' since it does not affect the count. Thus, the answer is 2 + 2 = 4.
Example 3:
Input: n = 1, pos = 0, k = 0
Output: 2
Explanation:
- There are no indices to the left or right of pos = 0.
- To see k = 0 people, no additional condition is required.
- The person at index 0 can choose 'L' or 'R'. Thus, the answer is 2.
Constraints:
1 <= n <= 10^50 <= pos, k <= n - 1
Solution
Approach: Combinatorics + Enumeration
There are pos people to the left of index pos and n - pos - 1 people to the right. Only the left people who choose 'L' and the right people who choose 'R' are seen.
Enumerate a, the number of visible people on the left, so b = k - a people must be visible on the right. When a <= pos and b <= n - pos - 1, there are C(pos, a) * C(n - pos - 1, b) ways to pick them, and the person at pos can choose either direction, which doubles the count. Sum 2 * C(pos, a) * C(n - pos - 1, b) over all valid a.
Binomial coefficients modulo 10^9 + 7 come from precomputed factorials and their modular inverses.
Complexity: time O(n), space O(n).
N = 100001
MOD = 10**9 + 7
f = [1] * N
g = [1] * N
for i in range(1, N):
f[i] = f[i - 1] * i % MOD
g[i] = pow(f[i], MOD - 2, MOD)
def comb(n, k):
return f[n] * g[k] * g[n - k] % MOD
class Solution:
def countVisiblePeople(self, n: int, pos: int, k: int) -> int:
l, r = pos, n - pos - 1
ans = 0
for a in range(min(k, l) + 1):
b = k - a
if b <= r:
ans += 2 * comb(l, a) * comb(r, b)
ans %= MOD
return ans