Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Domino and Tromino Tiling

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "790" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

You have two types of tiles: a 2 x 1 domino shape and a tromino shape. You may rotate these shapes. Given an integer n, return the number of ways to tile an 2 x n board. Since the answer may be very large, return it modulo 109 + 7. In a tiling, every square must be covered by a tile. Two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile. Example 1: Input: n = 3 Output: 5 Explanation: The five different ways are show above. Example 2: Input: n = 1 Output: 1 Constraints: 1 <= n <= 1000

Explanation

Here's a breakdown of the approach, followed by the Python code:

  • Dynamic Programming: We use dynamic programming to build up the solution iteratively. We define states representing the number of ways to tile a 2 x i board fully, and the number of ways to tile a 2 x i board with one square missing (either the top or bottom).

  • State Transitions: We derive the recurrence relations between these states based on how the last column can be filled using dominoes and trominoes. We need to consider the different orientations of trominoes and dominoes.

  • Modulo Arithmetic: Since the answer can be large, we perform modulo operations at each step to prevent overflow and keep the results within the desired range.

  • Runtime & Storage Complexity: O(n) time, O(n) space

Code

    def num_tilings(n: int) -> int:
    """
    Calculates the number of ways to tile a 2 x n board with dominoes and trominoes.

    Args:
        n: The length of the board.

    Returns:
        The number of ways to tile the board modulo 10^9 + 7.
    """

    MOD = 10**9 + 7

    if n <= 2:
        return n

    dp_full = [0] * (n + 1)  # Ways to tile 2 x i fully
    dp_partial = [0] * (n + 1)  # Ways to tile 2 x i with one cell missing

    dp_full[0] = 1
    dp_full[1] = 1
    dp_full[2] = 2
    dp_partial[1] = 1
    dp_partial[2] = 2

    for i in range(3, n + 1):
        dp_full[i] = (dp_full[i - 1] + dp_full[i - 2] + 2 * dp_partial[i - 1]) % MOD
        dp_partial[i] = (dp_partial[i - 1] + dp_full[i - 2]) % MOD

    return dp_full[n]

More from this blog

C

Chatmagic blog

2894 posts

Solving Leetcode Interviews in Seconds with AI: Domino and Tromino Tiling