Talentd
FleetCode
Make and follow sheets.Sign in

Find the Number of Possible Ways for an Event solution and explanation

HardCombinatoricsDynamic ProgrammingMath7 min read34.8% acceptanceUpdated 9 Apr 2026
Leetcode Biweekly Contest 141 | 3317. Find the Number of Possible Ways for an Event | CodefodCodeFod · 28:30 · 659 viewsWatch on YouTube
2 more videos on this problem
  1. Leetcode Biweekly Contest 141 | 3317. Find the Number of Possible Ways for an Event | CodefodCodeFod · 28:30 · 659 views
  2. 3317. Find the Number of Possible Ways for an Event (Leetcode Hard)Programming Live with Larry · 1:10:55 · 598 views
  3. Q4. Find the Number of Possible Ways for an Event | Leetcode Bieeekly-141 | Editorial #contestCodeLearnCode · 1:36 · 125 views

The problem

You are given three integers n, x, and y.

An event is being held for n performers. When a performer arrives, they are assigned to one of the x stages. All performers assigned to the same stage will perform together as a band, though some stages might remain empty.

After all performances are completed, the jury will award each band a score in the range [1, y].

Return the total number of possible ways the event can take place.

Since the answer may be very large, return it modulo 109 + 7.

Note that two events are considered to have been held differently if either of the following conditions is satisfied:

  • Any performer is assigned a different stage.
  • Any band is awarded a different score.

Example 1:

Input: n = 1, x = 2, y = 3

Output: 6

Explanation:

  • There are 2 ways to assign a stage to the performer.
  • The jury can award a score of either 1, 2, or 3 to the only band.

Example 2:

Input: n = 5, x = 2, y = 1

Output: 32

Explanation:

  • Each performer will be assigned either stage 1 or stage 2.
  • All bands will be awarded a score of 1.

Example 3:

Input: n = 3, x = 3, y = 4

Output: 684

Constraints:

  • 1 <= n, x, y <= 1000

Approach overview

Problem Overview: You have n participants, x available stages, and y possible score values for each stage. Participants are distributed across stages such that every used stage has at least one participant. Each used stage then receives one of the y score values. The task is to count the total number of valid configurations modulo 1e9+7.

The key observation: if exactly k stages are used, three independent choices happen. First distribute n participants into k non‑empty groups. Then map those groups to k distinct stages out of x. Finally assign a score to each used stage. Summing this count for all valid k gives the final answer.

Approach 1: Combinatorial Counting with Stirling Numbers (Time: O(n * min(n,x)), Space: O(n * min(n,x)))

This approach models the distribution of participants using Stirling numbers of the second kind. S(n, k) represents the number of ways to partition n items into k non‑empty groups. Once groups are formed, map them to k distinct stages using permutations P(x, k). Each used stage independently chooses a score from y possibilities, giving y^k choices. The total for a fixed k becomes S(n,k) * P(x,k) * y^k. Iterate k from 1 to min(n, x), accumulate the values modulo 1e9+7. This method relies heavily on combinatorics and factorial-based permutations.

Approach 2: Dynamic Programming for Stirling Numbers (Time: O(n * min(n,x)), Space: O(n * min(n,x)))

Instead of using a direct combinatorial formula, compute S(n,k) using the recurrence S(n,k) = S(n-1,k-1) + k * S(n-1,k). Build a DP table where rows represent participants and columns represent group counts. Each state represents how many ways participants can form k non‑empty groups. After computing the DP table, combine each S(n,k) with the permutation term P(x,k) and the scoring term y^k. Modular exponentiation handles the y^k factor efficiently. This formulation fits naturally with dynamic programming and avoids needing precomputed Stirling values.

Recommended for interviews: The combinatorial formulation with Stirling numbers is what interviewers usually expect for a hard counting problem involving labeled resources and non‑empty partitions. Showing the DP recurrence for S(n,k) demonstrates deeper understanding of math and combinatorial identities. Brute enumeration is infeasible due to exponential growth, so recognizing the partition‑then‑assign structure is the real insight.

Approach 1: Combinatorial Approach

This approach focuses on understanding the number of ways performers can be assigned to different stages and the number of scoring possibilities for the bands. We calculate the number of ways to assign performers to stages as x^n and multiply it by the number of scoring combinations for each band, which is y^x. Finally, result modulo 10^9 + 7 is returned.

def power_mod(base, exp, mod):
    result = 1
    while exp > 0:
        if exp % 2 == 1:
            result = (result * base) % mod
        base = (base * base) % mod
        exp //= 2
    return result

n = 3
x = 3
y = 4
MOD = 1000000007
stage_assignments = power_mod(x, n, MOD)
scoring_ways = power_mod(y, x, MOD)
result = (stage_assignments * scoring_ways) % MOD
print(result)
public class Main {
    private static final long MOD = 1000000007;

    public static long powerMod(long base, long exp, long mod) {
        long result = 1;
        while (exp > 0) {
            if ((exp % 2) == 1)
                result = (result * base) % mod;
            base = (base * base) % mod;
            exp /= 2;
        }
        return result;
    }

    public static void main(String[] args) {
        int n = 3, x = 3, y = 4;
        long stageAssignments = powerMod(x, n, MOD);
        long scoringWays = powerMod(y, x, MOD);
        long result = (stageAssignments * scoringWays) % MOD;
        System.out.println(result);
    }
}
#include <iostream>
using namespace std;
#define MOD 1000000007

typedef long long ll;

ll power_mod(ll base, ll exp, ll mod) {
    ll result = 1;
    while (exp > 0) {
        if (exp % 2 == 1)
            result = (result * base) % mod;
        base = (base * base) % mod;
        exp /= 2;
    }
    return result;
}

int main() {
    int n = 3, x = 3, y = 4;
    ll stageAssignments = power_mod(x, n, MOD);
    ll scoringWays = power_mod(y, x, MOD);
    ll result = (stageAssignments * scoringWays) % MOD;
    cout << result << endl;
    return 0;
}
const MOD = 1000000007;

function powerMod(base, exp, mod) {
    let result = 1;
    while (exp > 0) {
        if (exp % 2 === 1)
            result = (result * base) % mod;
        base = (base * base) % mod;
        exp = Math.floor(exp / 2);
    }
    return result;
}

let n = 3, x = 3, y = 4;
let stageAssignments = powerMod(x, n, MOD);
let scoringWays = powerMod(y, x, MOD);
let result = (stageAssignments * scoringWays) % MOD;
console.log(result);
#include <stdio.h>
#define MOD 1000000007

long long power_mod(long long base, long long exp, long long mod) {
    long long result = 1;
    while (exp > 0) {
        if (exp % 2 == 1) // Odd exponent
            result = (result * base) % mod;
        base = (base * base) % mod;
        exp /= 2;
    }
    return result;
}

int main() {
    int n = 3, x = 3, y = 4;
    long long stageAssignments = power_mod(x, n, MOD);
    long long scoringWays = power_mod(y, x, MOD);
    long long result = (stageAssignments * scoringWays) % MOD;
    printf("%lld\n", result);
    return 0;
}
using System;

class Program {
    const long MOD = 1000000007;

    static long PowerMod(long base, long exp, long mod) {
        long result = 1;
        while (exp > 0) {
            if ((exp % 2) == 1)
                result = (result * base) % mod;
            base = (base * base) % mod;
            exp /= 2;
        }
        return result;
    }

    static void Main() {
        int n = 3, x = 3, y = 4;
        long stageAssignments = PowerMod(x, n, MOD);
        long scoringWays = PowerMod(y, x, MOD);
        long result = (stageAssignments * scoringWays) % MOD;
        Console.WriteLine(result);
    }
}

This Python approach employs the efficient modular exponentiation method for calculating x^n % MOD and y^x % MOD. It offers an intuitive and clear way to solve the problem using functions.

Complexity

Time Complexity: O(log n + log x)
Space Complexity: O(1).

Try this approach in the editor

Approach 2: Dynamic Programming Approach

This approach utilizes dynamic programming to calculate the number of ways to assign performers to stages while also keeping track of scored bands. The idea is to build up a solution incrementally using previously computed results, which can be especially useful in cases where recursive approaches might lead to computation of the same sub-problems.

def number_of_ways(n, x, y):
    MOD = 1000000007
    dp = [0] * (n + 1)
    dp[0] = 1
    for i in range(1, n + 1):
        dp[i] = (dp[i - 1] * x) % MOD
    score_combinations = pow(y, x, MOD)
    result = (dp[n] * score_combinations) % MOD
    return result

n, x, y = 3, 3, 4
print(number_of_ways(n, x, y))
public class Main {
    private static final long MOD = 1000000007;

    public static void main(String[] args) {
        int n = 3, x = 3, y = 4;
        long[] dp = new long[n + 1];
        dp[0] = 1;
        for (int i = 1; i <= n; i++) {
            dp[i] = (dp[i - 1] * x) % MOD;
        }
        long scoreCombination = 1;
        for (int i = 0; i < x; i++) {
            scoreCombination = (scoreCombination * y) % MOD;
        }
        long result = (dp[n] * scoreCombination) % MOD;
        System.out.println(result);
    }
}
#include <iostream>
#include <vector>
using namespace std;
#define MOD 1000000007

typedef long long ll;

int main() {
    int n = 3, x = 3, y = 4;
    vector<ll> dp(n + 1, 0);
    dp[0] = 1;
    for (int i = 1; i <= n; ++i) {
        dp[i] = (dp[i - 1] * x) % MOD;
    }
    ll scoreCombination = 1;
    for (int i = 0; i < x; ++i) {
        scoreCombination = (scoreCombination * y) % MOD;
    }
    ll result = (dp[n] * scoreCombination) % MOD;
    cout << result << endl;
    return 0;
}
const MOD = 1000000007;

function numberOfWays(n, x, y) {
    const dp = new Array(n + 1).fill(0);
    dp[0] = 1;
    for (let i = 1; i <= n; i++) {
        dp[i] = (dp[i - 1] * x) % MOD;
    }
    const scoreCombinations = BigInt(Math.pow(y, x) % MOD);
    const result = BigInt(dp[n]) * scoreCombinations % BigInt(MOD);
    return Number(result);
}

const n = 3, x = 3, y = 4;
console.log(numberOfWays(n, x, y));
#include <stdio.h>
#define MOD 1000000007

int main() {
    int n = 3, x = 3, y = 4;
    long long ways[n + 1];
    for (int i = 0; i <= n; ++i) ways[i] = 0;
    ways[0] = 1;
    
    for (int i = 1; i <= n; ++i) {
        ways[i] = (ways[i - 1] * x) % MOD;
    }
    long long scoreCombinations = 1;
    for (int i = 0; i < x; ++i) {
        scoreCombinations = (scoreCombinations * y) % MOD;
    }
    long long result = (ways[n] * scoreCombinations) % MOD;
    printf("%lld\n", result);
    
    return 0;
}
using System;
class Program {
    const long MOD = 1000000007;
    static void Main() {
        int n = 3, x = 3, y = 4;
        long[] dp = new long[n + 1];
        dp[0] = 1;
        for (int i = 1; i <= n; i++) {
            dp[i] = (dp[i - 1] * x) % MOD;
        }
        long scoreCombination = 1;
        for (int i = 0; i < x; i++) {
            scoreCombination = (scoreCombination * y) % MOD;
        }
        long result = (dp[n] * scoreCombination) % MOD;
        Console.WriteLine(result);
    }
}

This Python solution maintains states using a list to dynamically store computation progress, effectively solving the problem by exploiting known states to avoid redundant computations.

Complexity

Time Complexity: O(n + x)
Space Complexity: O(n).

Try this approach in the editor

Approach 3: Dynamic Programming

We define f[i][j] to represent the number of ways to arrange the first i performers into j programs. Initially, f[0][0] = 1, and the rest f[i][j] = 0.

For f[i][j], where 1 leq i leq n and 1 leq j leq x, we consider the i-th performer:

  • If the performer is assigned to a program that already has performers, there are j choices, i.e., f[i - 1][j] times j;
  • If the performer is assigned to a program that has no performers, there are x - (j - 1) choices, i.e., f[i - 1][j - 1] times (x - (j - 1)).

So the state transition equation is:

$ f[i][j] = f[i - 1][j] times j + f[i - 1][j - 1] times (x - (j - 1))

For each j, there are y^j choices, so the final answer is:

sum_{j = 1}^{x} f[n][j] times y^j

Note that since the answer can be very large, we need to take the modulo 10^9 + 7.

The time complexity is O(n times x), and the space complexity is O(n times x). Here, n and x$ represent the number of performers and the number of programs, respectively.

function numberOfWays(n: number, x: number, y: number): number {
    const mod = BigInt(10 ** 9 + 7);
    const f: bigint[][] = Array.from({ length: n + 1 }, () => Array(x + 1).fill(0n));
    f[0][0] = 1n;
    for (let i = 1; i <= n; ++i) {
        for (let j = 1; j <= x; ++j) {
            f[i][j] = (f[i - 1][j] * BigInt(j) + f[i - 1][j - 1] * BigInt(x - (j - 1))) % mod;
        }
    }
    let [ans, p] = [0n, 1n];
    for (let j = 1; j <= x; ++j) {
        p = (p * BigInt(y)) % mod;
        ans = (ans + f[n][j] * p) % mod;
    }
    return Number(ans);
}
func numberOfWays(n int, x int, y int) int {
	const mod int = 1e9 + 7
	f := make([][]int, n+1)
	for i := range f {
		f[i] = make([]int, x+1)
	}
	f[0][0] = 1
	for i := 1; i <= n; i++ {
		for j := 1; j <= x; j++ {
			f[i][j] = (f[i-1][j]*j%mod + f[i-1][j-1]*(x-(j-1))%mod) % mod
		}
	}
	ans, p := 0, 1
	for j := 1; j <= x; j++ {
		p = p * y % mod
		ans = (ans + f[n][j]*p%mod) % mod
	}
	return ans
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Combinatorial Approach

Time Complexity: O(log n + log x)
Space Complexity: O(1).

Dynamic Programming Approach

Time Complexity: O(n + x)
Space Complexity: O(n).

Dynamic Programming–

Complexity analysis

ApproachTimeSpaceWhen to Use
Combinatorial Counting with Stirling NumbersO(n · min(n,x))O(n · min(n,x))Best general solution when using combinatorics and modular arithmetic
Dynamic Programming for Stirling NumbersO(n · min(n,x))O(n · min(n,x))Useful when deriving Stirling values directly with DP

Frequently asked questions

Is Find the Number of Possible Ways for an Event easy or hard?

LeetCode classifies this problem as Hard. It requires recognizing the partition structure, applying Stirling numbers of the second kind, and combining them with permutations and modular exponentiation.

Find the Number of Possible Ways for an Event Python/Java solution

Python and Java implementations typically build a DP table for Stirling numbers, then iterate over k from 1 to min(n,x). Each term S(n,k) is multiplied by P(x,k) and pow(y,k,MOD) to accumulate the final answer under modulo 1e9+7.

How to solve Find the Number of Possible Ways for an Event in O(n)?

An exact O(n) solution generally isn't used because the computation requires values for multiple k up to min(n,x). The practical optimal approach computes Stirling numbers with DP in O(n·min(n,x)) time, then combines them with permutations and fast exponentiation.

What is the best approach for Find the Number of Possible Ways for an Event?

The best approach uses combinatorics with Stirling numbers of the second kind. For each possible number of used stages k, compute S(n,k) ways to partition participants, multiply by P(x,k) ways to map groups to stages, and multiply by y^k score assignments. Summing over k from 1 to min(n,x) gives the answer in O(n·min(n,x)) time.

Is Find the Number of Possible Ways for an Event asked at Google/Amazon/Meta?

This style of problem appears in interviews at companies like Google, Amazon, and Meta when testing advanced counting techniques. It combines combinatorics, dynamic programming, and modular arithmetic, which are common in senior-level algorithm interviews.

What data structure is used in Find the Number of Possible Ways for an Event?

The core structure is a dynamic programming table used to compute Stirling numbers S(n,k). Along with this table, the solution relies on factorial or permutation calculations and fast modular exponentiation for the y^k term.

What is the time complexity of Find the Number of Possible Ways for an Event?

The typical solution runs in O(n · min(n, x)) time. This cost comes from computing Stirling numbers S(n,k) using dynamic programming and iterating over all possible values of k. Space complexity is also O(n · min(n,x)) for the DP table.

Comments

Now write it yourselfClose this page and solve Find the Number of Possible Ways for an Event in the editor, without looking.
Practise Find the Number of Possible Ways for an Event