Problem 1155

Abstract / Summary

Find how many ways rolling dice with given faces and rolls can total a specific sum.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1155.py

class Solution:
    def numRollsToTarget(self, n: int, k: int, target: int) -> int:
        todo = defaultdict(int)
        todo[0] = 1
        for m in range(n):
            next = defaultdict(int)
            for i in range(target):
                for j in range(k, 0, -1):
                    if i + j <= target:
                        next[i + j] += todo[i]
            todo = next
        return todo[target] % 1_000_000_007
12 lines | 444 bytes | submitted December 26, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 63% (500k+ submissions).

Typical patterns to solve this problem:
  • Dynamic Programming
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation computes the number of distinct ways to roll n dice, each with k faces numbered from 1 to k, such that the sum of the face values equals a given target. The algorithm builds the solution incrementally, processing one die at a time and maintaining a mapping from achievable intermediate sums to the count of ways those sums can be formed. After all dice have been considered, the count associated with the exact target sum is returned modulo 1 000 000 007.

Initialization of the dynamic-state container

The algorithm begins by creating a dictionary-like structure that defaults missing keys to zero. The entry for sum 0 is seeded with a count of 1, representing the single way to achieve a sum of zero before any dice are rolled.

todo = defaultdict(int)
todo[0] = 1

This setup establishes the base case for the dynamic programming recurrence.

Iterative processing of each die

A loop runs exactly n times, once for each die. Inside the loop a fresh dictionary next is prepared to collect the new counts that result from adding the current die’s face value to every previously reachable sum.

for m in range(n):
    next = defaultdict(int)
    # inner accumulation follows
    todo = next

The variable m itself is not used; its purpose is solely to repeat the inner logic n times.

Accumulating counts for reachable sums

For every intermediate sum i that is currently reachable (i.e., i ranges from 0 up to target-1), the algorithm iterates over all possible face values j from k down to 1. The descending order of j does not affect correctness but may improve cache locality in some Python implementations. A conditional guard ensures that only sums that do not exceed target are considered; attempts to exceed the target are silently ignored, which naturally prunes impossible branches.

for i in range(target):
    for j in range(k, 0, -1):
        if i + j <= target:
            next[i + j] += todo[i]

When the condition holds, the count for the new sum i + j is incremented by the number of ways to achieve the previous sum i. Because todo is a defaultdict, missing entries contribute zero without explicit checks.

Final result extraction

After all dice have been processed, the dictionary todo holds the counts for every sum that can be formed with exactly n dice. The answer is the entry for target, reduced modulo the large prime 1 000 000 007 to keep the result within the required range.

return todo[target] % 1_000_000_007

If target was never reached, the defaultdict supplies a zero, yielding the correct answer of zero ways.

Edge-case handling

The code gracefully handles the situation where no dice are rolled (n == 0). In that case the outer loop does not execute, leaving todo unchanged with only the entry {0: 1}. Consequently, a target of zero returns 1 (the empty roll), while any positive target returns 0, matching the combinatorial expectation.

When target is zero but n is positive, the inner loop iterates over i in range(0), producing no updates. After the first die, todo becomes empty, and the final lookup yields zero ways, which is correct because a positive number of dice cannot sum to zero when each face value is at least 1.

The conditional if i + j <= target prevents attempts to index sums beyond the desired bound, thereby avoiding unnecessary work and ensuring that the dictionary never stores keys larger than target.

Performance-related choices

The algorithm relies on a sparse representation of the state space via defaultdict. This avoids allocating a full array of size target + 1 for each iteration, which can be advantageous when many entries remain zero, especially for large target values relative to n and k.

By iterating i only up to target - 1 and checking the sum bound before updating, the inner loop eliminates a whole class of impossible transitions early, reducing the number of arithmetic operations.

The modulo operation is deferred until the final return. This choice reduces the overhead of repeated modular reductions during the accumulation phase, allowing Python’s arbitrary-precision integers to grow temporarily but avoiding the cost of a modulus per addition.

The descending order of the face-value loop (range(k, 0, -1)) can improve branch prediction and memory access patterns in CPython’s interpreter loop, offering a modest speed benefit without affecting the algorithmic result.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a set of dice and you want to see how many different ways you can roll them to get a specific total number. The computer uses a box called todo to keep track of the scores it has reached so far. At the very beginning, the only score reached is zero because no dice have been rolled yet.

The code starts a loop that runs once for every single die you have. Inside that loop, it creates a new empty box because the old scores are not useful anymore once you add a new die. Then, it looks at every current score in the first box and adds the value of a new die flip to it. Every time the computer finds a way to reach a new total sum, it writes that down in the next box.

After checking all the possible dice rolls, the old box is replaced by the new one filled with the updated results. This happens over and over again until all the dice have been thrown. By the end, the computer looks at the final box to see how many paths led to the exact target number you wanted to find.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 5.81 | σ = 1.42

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster Java C++ Python TS
WalkCCC Java C++ Python
leetcode.ca Java C++ Python Go Rust TS
Progiez Java C++ Python
github black-shadows C++
charles-wangkai Java
everthis JS
fpdjsns C++
fsq C++
gouthampradhan Java
JoshCrozier JS
lkwq007 Python
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fpdjsns C++
fsq C++
gouthampradhan Java
JoshCrozier JavaScript
lkwq007 Python
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
28 links | 16 authors | 8 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

5 solutions   December 26, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality