#790

Domino and Tromino Tiling

Medium
Dynamic ProgrammingDynamic ProgrammingRecursionMemoization
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses dynamic programming to build up the number of ways to tile the board from smaller subproblems. This avoids redundant calculations and allows us to compute the result in linear time.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create an array dp of size n+1 to store the number of ways to tile the board of length i.
  2. 2Step 2: Initialize dp[0] = 1, dp[1] = 1, dp[2] = 2 (base cases).
  3. 3Step 3: Iterate from 3 to n, calculating dp[i] as dp[i-1] + dp[i-2] + 2 * dp[i-3] (considering the placements of dominoes and trominoes).
  4. 4Step 4: Return dp[n] modulo 10^9 + 7.
solution.py9 lines
1# Full working Python code
2MOD = 10**9 + 7
3
4def numTilings(n):
5    dp = [0] * (n + 1)
6    dp[0], dp[1], dp[2] = 1, 1, 2
7    for i in range(3, n + 1):
8        dp[i] = (dp[i - 1] + dp[i - 2] + 2 * dp[i - 3]) % MOD
9    return dp[n]

Complexity note: The time complexity is O(n) because we compute the number of ways to tile the board for each length from 3 to n once. The space complexity is O(n) due to the storage of results in the dp array.

  • 1Understanding how to break down the problem into smaller subproblems is crucial for dynamic programming.
  • 2Recognizing the base cases helps in building the solution iteratively.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.