LeetCode in Kotlin

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

import kotlin.math.min

class Solution {
    fun countVisiblePeople(n: Int, pos: Int, k: Int): Int {
        val total = n - 1
        val combinations = nCr(total, k)
        return (2L * combinations % MOD).toInt()
    }

    private fun nCr(n: Int, r: Int): Long {
        var r = r
        r = min(r, n - r)
        var numerator: Long = 1
        var denominator: Long = 1
        for (i in 1..r) {
            numerator = numerator * (n - r + i) % MOD
            denominator = denominator * i % MOD
        }
        return numerator * modPow(denominator, MOD - 2) % MOD
    }

    private fun modPow(base: Long, exponent: Long): Long {
        var base = base
        var exponent = exponent
        var result: Long = 1
        while (exponent > 0) {
            if ((exponent and 1L) == 1L) {
                result = result * base % MOD
            }

            base = base * base % MOD
            exponent = exponent shr 1
        }
        return result
    }

    companion object {
        private const val MOD = 1000000007L
    }
}