#3881
Direction Assignments with Exactly K Visible People
MediumApproaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | Unknown |
| Space | O(1) | Unknown |
💡
Intuition
Time UnknownSpace Unknown
Use combinatorial counting to determine how many people can be assigned directions such that exactly k are visible. This avoids generating all combinations.
⚙️
Algorithm
3 steps- 1Step 1: Calculate the number of people to the left (a = pos) and to the right (b = n - pos - 1).
- 2Step 2: Use combinatorial functions to count valid configurations for left and right based on k.
- 3Step 3: Combine results from left and right configurations to get the total.
solution.py9 lines
1def countVisible(n, pos, k):
2 from math import comb
3 a, b = pos, n - pos - 1
4 total = 0
5 for left in range(max(0, k - b), min(a, k) + 1):
6 right = k - left
7 if 0 <= right <= b:
8 total += comb(a, left) * comb(b, right)
9 return total % (10**9 + 7)Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.