Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Game of Life

Updated
3 min read

Introduction

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

According to Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970." The board is made up of an m x n grid of cells, where each cell has an initial state: live (represented by a 1) or dead (represented by a 0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article): Any live cell with fewer than two live neighbors dies as if caused by under-population. Any live cell with two or three live neighbors lives on to the next generation. Any live cell with more than three live neighbors dies, as if by over-population. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction. The next state of the board is determined by applying the above rules simultaneously to every cell in the current state of the m x n grid board. In this process, births and deaths occur simultaneously. Given the current state of the board, update the board to reflect its next state. Note that you do not need to return anything. Example 1: Input: board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]] Output: [[0,0,0],[1,0,1],[0,1,1],[0,1,0]] Example 2: Input: board = [[1,1],[1,0]] Output: [[1,1],[1,1]] Constraints: m == board.length n == board[i].length 1 <= m, n <= 25 board[i][j] is 0 or 1. Follow up: Could you solve it in-place? Remember that the board needs to be updated simultaneously: You cannot update some cells first and then use their updated values to update other cells. In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches upon the border of the array (i.e., live cells reach the border). How would you address these problems?

Explanation

  • In-place update using encoded states: Instead of creating a new board, modify the original board in-place. Use encoded states to represent the next state of a cell without overwriting the current state. For instance, use 2 to represent a dead cell becoming alive, and -1 to represent a live cell dying.
    • Iterate and count neighbors: Iterate through each cell in the board. For each cell, count its live neighbors. Apply the rules of Conway's Game of Life to determine the next state.
    • Decode the encoded states: After processing all cells, iterate through the board again to decode the encoded states (2 becomes 1, and -1 becomes 0) to reflect the final next state.
  • Runtime Complexity: O(m*n), where m is the number of rows and n is the number of columns in the board.
  • Storage Complexity: O(1) (in-place modification)

Code

    class Solution:
    def gameOfLife(self, board: list[list[int]]) -> None:
        """
        Do not return anything, modify board in-place instead.
        """
        rows = len(board)
        cols = len(board[0])

        def count_live_neighbors(row, col):
            count = 0
            for i in range(max(0, row - 1), min(rows, row + 2)):
                for j in range(max(0, col - 1), min(cols, col + 2)):
                    if (i, j) != (row, col) and abs(board[i][j]) == 1:
                        count += 1
            return count

        for row in range(rows):
            for col in range(cols):
                live_neighbors = count_live_neighbors(row, col)

                if board[row][col] == 1 and (live_neighbors < 2 or live_neighbors > 3):
                    board[row][col] = -1  # Mark as dying
                elif board[row][col] == 0 and live_neighbors == 3:
                    board[row][col] = 2  # Mark as becoming alive

        for row in range(rows):
            for col in range(cols):
                if board[row][col] == 2:
                    board[row][col] = 1
                elif board[row][col] == -1:
                    board[row][col] = 0

More from this blog

C

Chatmagic blog

2894 posts