#502 - Counting Castles
We define a block to be a rectangle with a height of \(1\) and an integer-valued length. Let a castle be a configuration of stacked blocks.
Given a game grid that is \(w\) units wide and \(h\) units tall, a castle is generated according to the following rules:
- Blocks can be placed on top of other blocks as long as nothing sticks out past the edges or hangs out over open space.
- All blocks are aligned/snapped to the grid.
- Any two neighboring blocks on the same row have at least one unit of space between them.
- The bottom row is occupied by a block of length \(w\).
- The maximum achieved height of the entire castle is exactly \(h\).
- The castle is made from an even number of blocks.
The following is a sample castle for \(w=8\) and \(h=5\):

Let \(F(w,h)\) represent the number of valid castles, given grid parameters \(w\) and \(h\).
For example, \(F(4,2) = 10\), \(F(13,10) = 3729050610636\), \(F(10,13) = 37959702514\), and \(F(100,100) \bmod 1\,000\,000\,007 = 841913936\).
Find \((F(10^{12},100) + F(10000,10000) + F(100,10^{12})) \bmod 1\,000\,000\,007\).
Problem text © Project Euler, licensed under CC BY-NC-SA 4.0. Original: projecteuler.net/problem=502. Published Saturday, 7th February 2015, 04:00 pm. Solved by 370 members at time of mirroring.
Why this is useful
Algorithmic Development. Optimal substructure and state-space reasoning are exactly how American-option pricing and optimal execution are solved (Phases 13, 16).
We classify relevance honestly - not every Euler problem is a trading application.
Prerequisites
Lessons that prepare you:
19.8 Bit Manipulation and State Compression · 19.5 Combinatorics: Counting, Binomials, and Inclusion–Exclusion · 19.14 Computational Complexity, Feasibility Estimation, and Proving Algorithms Correct · 19.7 Dynamic Programming: Memoization and Tabulation · 19.9 Graph Algorithms: BFS, DFS, Dijkstra, and Minimum Spanning Trees · 19.10 Search: Backtracking, Branch-and-Bound, Binary Search, Meet-in-the-Middle · 3.1 Vectors, Multivariable Functions, and Level Sets
Recommended stepping-stone problems: #436 · #488 · #870
Concepts: game-theory geometry graph-theory brute-force-reduction
Likely techniques: bitmask-dp inclusion-exclusion
Learning mode
Pick how much scaffolding you want. Your choice is remembered per problem.
Understand the problem
- What exactly is the input to problem 502? Is it a bound (10^12), a supplied dataset, or a definition you must generate from?
- What is the required output - restate it precisely: a single residue (the answer is reduced modulo a given number, so keep everything in modular arithmetic from the start).
- Write out, in your own words, the definition of block as the statement gives it. Which integers/objects are excluded by that definition?
- What do the arguments of F(w,h), F(4,2) mean, and what is the value's type (count, sum, probability)?
- What are the edge cases: the smallest legal object, zero/one, ties, and the boundary at exactly 10^12?
- Why is brute force hard HERE specifically? Estimate the number of candidates implied by 10^12 and the cost of testing one.
- Which game-theory fact would, if true, collapse the search - and can you state it as a testable claim before you look for a proof?
Predict & plan (before you code)
- Predict the strategy: in one sentence, what will your solution do? (The classification says game-theory / bitmask-dp - do you agree, and why?)
- Predict the complexity of your intended method in terms of N = 10^12, and the wall-clock time you expect. Write both down now.
- Predict the key data structure: what is stored, keyed by what, and how large will it get at full scale?
- Predict the failure mode: what is most likely to break - an off-by-one on the bound, a definition misread, precision, or memory?
- Predict the output of the small case from rung 3 BEFORE running it (the statement says: "For example, F(4,2) = 10, F(13,10) = 3729050610636, F(10,13) = 37959702514, and F(100,100) mod 1000000007 = 841913936.") - then run it. A surprise here is worth more than an hour of debugging later.
Scratchpad
Mathematical notes, formulas, pseudocode, hypotheses, complexity notes. Saved automatically with your progress.
Python workbench
Real Python (Pyodide) in a sandboxed Web Worker - no network, no filesystem, no DOM access. Ctrl/Cmd+Enter runs. Escape leaves the editor. Stop terminates the worker.
Check your answer
Answers are checked against a salted hash held in a separate file - not printed in this page. This prevents accidental spoilers; it is not cryptographic protection (see the build notes).
Progressive hints
Optimization
You have a correct answer. That is the start of the learning, not the end.
- Reduce the time complexity. What is the bottleneck, and what mathematical fact removes it?
- Reduce memory. Can you stream, or keep only the last k states?
- Replace brute force with a closed form, a sieve, a recurrence, or a symmetry argument.
- Prove the optimized version computes the same thing.
- Compare two implementations and time them.
Explain it
Which step of your solution were you least confident about, and what evidence would settle it?
What did you try first, and what specifically made you abandon it - a proof, a timing, or a wrong small-case answer?
Where did the game-theory structure do the real work? Name the single observation that collapsed the search space.
Could you have reached the bitmask-dp idea faster? Which words in the statement were pointing at it, and did you notice them?
What was the bug that cost you the most time, and what CLASS of bug was it (off-by-one, definition misread, precision, state under-specified)?
How would your solution change if the bound 10^12 were multiplied by 1000? Does it survive, or does it need a different idea?
What is the honest complexity of what you wrote (not what you intended), and where is the remaining slack?
Which problem you have already solved is this most similar to, and what is the shared skeleton - is it really 'bitmask-dp' underneath?
State the transferable technique in one sentence, without mentioning this problem's story at all.
Self-assess (mastery is not a correct number)
You reach Mastered only when you have solved it, rated yourself at least Solid across the dimensions, and written a real explanation.
Confidence
Low confidence schedules this problem for spaced review, even if you solved it.
Mastery check
- Variation: change the bound (or a rule) in the statement. Does your method still work? What breaks first?
- Constraints: if the limit were 10× larger, which step fails, and what would you replace it with?
- Related problem: #436 · #488 · #870
- Transfer: where else does this technique appear? Name a lesson and a real computational setting.
- Spaced re-attempt: come back after the review interval and re-solve it with no hints.