Back to challenges
Medium 0 solved 0% acceptance

Count Dice Sequences

Count ordered die-roll sequences with a given total.

What you'll learn

  • Build answers from smaller totals
  • Write a recurrence over the last die roll
  • Take results modulo a large prime

Problem

A standard die produces an integer from 1 through 6. Count all nonempty ordered sequences of outcomes whose sum is target. Different orders count separately. Return the count modulo 1,000,000,007.

Implement dice_combinations(target).

Input

target: The required sum of all rolls.

Output

Return the number of sequences modulo 1,000,000,007.

Constraints

1 ≤ target ≤ 1,000,000. Taking a count modulo 1,000,000,007 means returning its remainder after division by that number.

Examples

Example 1
Input:
target = 2

Expected output:
expected = 2
Input:
long long target = 2;

Expected output:
long long expected = 2;
Input:
long target = 2;

Expected output:
long expected = 2;

Explanation

The two sequences are [2] and [1, 1].

Example 2
Input:
target = 4

Expected output:
expected = 8
Input:
long long target = 4;

Expected output:
long long expected = 8;
Input:
long target = 4;

Expected output:
long expected = 8;

Explanation

The sequences are [4], [1,3], [3,1], [2,2], [1,1,2], [1,2,1], [2,1,1], and [1,1,1,1].

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

Think of smaller sums as building blocks for the target.

Hint 2

Use a running count for each sum based on the previous six sums.

Hint 3

Be careful to apply the modulo at every addition and handle sums below 1 separately.

Expected complexity

O(target) time, O(target) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.