Advent of Code 2025 Day 11: Memoization Transforms Exponential Problems

🎄 Advent of Code 2025 – Day 11 Complete Wrapped up Day 11 of Advent of Code. This one was an elegant demonstration of how memoization transforms exponential problems into tractable ones. 𝗧𝗵𝗲 𝗖𝗵𝗮𝗹𝗹𝗲𝗻𝗴𝗲 The input describes a directed graph where each node points to its children, ultimately leading to an 'out' node. 𝗣𝗮𝗿𝘁 1: Count all possible paths from a starting node ('you') to the destination ('out'). 𝗣𝗮𝗿𝘁 2: Count only the paths that pass through specific required nodes ('dac' AND 'fft') before reaching the destination. 𝗪𝗵𝗮𝘁 𝗠𝗮𝗱𝗲 𝗜𝘁 𝗜𝗻𝘁𝗲𝗿𝗲𝘀𝘁𝗶𝗻𝗴 Part 1 is a classic recursive path counting problem. The naive approach recalculates the same subproblems repeatedly, leading to exponential time complexity. Adding @cache (memoization) transforms it into a dynamic programming solution that computes each node's result exactly once. Part 2 adds a twist: constraint tracking. We need to count only paths that satisfy certain conditions. The solution tracks which required nodes have been visited using a frozenset as part of the state space. This allows us to maintain memoization while ensuring we only count valid paths. The key insight: state space design matters. By using (node, visited_required_nodes) as our state, we keep the cache size manageable at O(nodes × 2^k) where k is the number of required nodes. 𝗞𝗲𝘆 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆𝘀: • Memoization: exponential → polynomial time complexity • State space design is crucial for efficient DP • Python's @cache decorator makes memoization trivial • Adding constraints requires careful state tracking • Frozensets enable hashable collections for caching 𝗣𝗲𝗿𝗳𝗼𝗿𝗺𝗮𝗻𝗰𝗲 𝗜𝗺𝗽𝗮𝗰𝘁: Without memoization: Would timeout on large graphs With memoization: Instant results ⚡ This problem perfectly illustrates why dynamic programming is one of the most powerful optimization techniques in computer science. 🔗 Code Repository: https://lnkd.in/eYRvn-mk #AdventOfCode #DynamicProgramming #Algorithms #GraphTheory #Python #Memoization #ComputationalThinking #SoftwareEngineering #ProblemSolving

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories