Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Construct Product Matrix

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "2906" 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

Given a 0-indexed 2D integer matrix grid of size n m, we define a 0-indexed 2D matrix p of size n m as the product matrix of grid if the following condition is met: Each element p[i][j] is calculated as the product of all elements in grid except for the element grid[i][j]. This product is then taken modulo 12345. Return the product matrix of grid. Example 1: Input: grid = [[1,2],[3,4]] Output: [[24,12],[8,6]] Explanation: p[0][0] = grid[0][1] grid[1][0] grid[1][1] = 2 3 4 = 24 p[0][1] = grid[0][0] grid[1][0] grid[1][1] = 1 3 4 = 12 p[1][0] = grid[0][0] grid[0][1] grid[1][1] = 1 2 4 = 8 p[1][1] = grid[0][0] grid[0][1] grid[1][0] = 1 2 3 = 6 So the answer is [[24,12],[8,6]]. Example 2: Input: grid = [[12345],[2],[1]] Output: [[2],[0],[0]] Explanation: p[0][0] = grid[0][1] grid[0][2] = 2 1 = 2. p[0][1] = grid[0][0] grid[0][2] = 12345 1 = 12345. 12345 % 12345 = 0. So p[0][1] = 0. p[0][2] = grid[0][0] grid[0][1] = 12345 2 = 24690. 24690 % 12345 = 0. So p[0][2] = 0. So the answer is [[2],[0],[0]]. Constraints: 1 <= n == grid.length <= 105 1 <= m == grid[i].length <= 105 2 <= n * m <= 105 1 <= grid[i][j] <= 109

Explanation

Here's an efficient solution to calculate the product matrix with modular arithmetic:

  • Overall Product: Calculate the product of all elements in the grid modulo 12345.
  • Division (Multiplicative Inverse): For each element, if it's non-zero, compute its contribution to the overall product and efficiently "divide" it out (using modular inverse if needed) to get the product of the remaining elements. If the grid contains zero(s), we handle them separately.
  • Zero Handling: If there's one zero in the grid, the product for every other element will be zero. If there are multiple zeros, the product for every element is zero, because at least one zero will always be included in the product.

  • Time Complexity: O(n*m). Space Complexity: O(n*m)

Code

    def product_matrix(grid: list[list[int]]) -> list[list[int]]:
    """
    Calculates the product matrix of a given 2D integer matrix with modular arithmetic.

    Args:
        grid: A 0-indexed 2D integer matrix.

    Returns:
        The product matrix of grid.
    """

    n = len(grid)
    m = len(grid[0])
    p = [[0] * m for _ in range(n)]
    MOD = 12345

    total_product = 1
    zero_count = 0
    for i in range(n):
        for j in range(m):
            if grid[i][j] == 0:
                zero_count += 1
            else:
                total_product = (total_product * grid[i][j]) % MOD

    if zero_count > 1:
        return p  # All elements will be 0

    for i in range(n):
        for j in range(m):
            if zero_count == 1:
                if grid[i][j] == 0:
                    p[i][j] = total_product
            else:
                if grid[i][j] != 0:
                    # Calculate modular inverse
                    a = grid[i][j] % MOD
                    inv = pow(a, MOD - 2, MOD)  # Modular inverse using Fermat's Little Theorem
                    p[i][j] = (total_product * inv) % MOD
                else:
                    p[i][j] = total_product

    return p

More from this blog

C

Chatmagic blog

2894 posts