LeetCode-in-Java

3881. Direction Assignments with Exactly K Visible People

Medium

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:

A person at index pos sees others as follows:

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 109 + 7.

Example 1:

Input: n = 3, pos = 1, k = 0

Output: 2

Explanation:

Example 2:

Input: n = 3, pos = 2, k = 1

Output: 4

Explanation:

Example 3:

Input: n = 1, pos = 0, k = 0

Output: 2

Explanation:

Constraints:

Solution

@SuppressWarnings("java:S1172")
public class Solution {
    private static final long MOD = 1_000_000_007L;

    public int countVisiblePeople(int n, int pos, int k) {
        int total = n - 1;
        long combinations = nCr(total, k);
        return (int) (2L * combinations % MOD);
    }

    private long nCr(int n, int r) {
        r = Math.min(r, n - r);
        long numerator = 1;
        long denominator = 1;
        for (int i = 1; i <= r; i++) {
            numerator = numerator * (n - r + i) % MOD;
            denominator = denominator * i % MOD;
        }
        return numerator * modPow(denominator, MOD - 2) % MOD;
    }

    private long modPow(long base, long exponent) {
        long result = 1;
        while (exponent > 0) {
            if ((exponent & 1) == 1) {
                result = result * base % MOD;
            }

            base = base * base % MOD;
            exponent >>= 1;
        }
        return result;
    }
}