Counting Tilings - Problem

You are given a 3 × N grid and need to tile it completely using 2 × 1 dominoes. Each domino can be placed either horizontally (covering 2 horizontally adjacent cells) or vertically (covering 2 vertically adjacent cells).

Return the number of ways to completely tile the 3 × N grid. Since the answer can be very large, return it modulo 109 + 7.

Note: The grid must be completely covered with no overlapping dominoes and no empty cells.

Input & Output

Example 1 — Basic Even Case
$ Input: n = 2
Output: 3
💡 Note: For a 3×2 grid, there are 3 ways to tile: (1) Three horizontal dominoes stacked vertically, (2) One vertical domino on left + horizontal domino on right, (3) Horizontal domino on left + one vertical domino on right
Example 2 — Larger Even Case
$ Input: n = 4
Output: 11
💡 Note: For a 3×4 grid, there are 11 different ways to completely tile using 2×1 dominoes
Example 3 — Odd Case (Impossible)
$ Input: n = 3
Output: 0
💡 Note: A 3×3 grid has 9 cells total, but each domino covers 2 cells, so it's impossible to tile completely (9 is odd)

Constraints

  • 0 ≤ n ≤ 1000
  • Answer fits in 32-bit integer after modulo

Visualization

Tap to expand
INPUTALGORITHMRESULT3×4 Grid12 cells totalNeed 6 dominoes1Bitmask States000, 001, 010, 011100, 101, 110, 1112DP TransitionsFor each column state,compute valid next states3Column ProcessingProcess left to right,track ways per state4Final CountWays to reach empty statein final column11Total Waysto tile 3×4 gridEach way representsa complete valid tilingwith 6 dominoesKey Insight:Instead of trying all possible domino placements, use bitmask DP to trackcolumn states efficiently. Each column has only 8 possible completion states,allowing O(N) time complexity instead of exponential enumeration.TutorialsPoint - Counting Tilings | Bitmask Dynamic Programming
Asked in
Google 12 Facebook 8 Microsoft 6 Amazon 4
28.5K Views
Medium Frequency
~35 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen