Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Battleships in a Board

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "419" 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 an m x n matrix board where each cell is a battleship 'X' or empty '.', return the number of the battleships on board. Battleships can only be placed horizontally or vertically on board. In other words, they can only be made of the shape 1 x k (1 row, k columns) or k x 1 (k rows, 1 column), where k can be of any size. At least one horizontal or vertical cell separates between two battleships (i.e., there are no adjacent battleships). Example 1: Input: board = [["X",".",".","X"],[".",".",".","X"],[".",".",".","X"]] Output: 2 Example 2: Input: board = [["."]] Output: 0 Constraints: m == board.length n == board[i].length 1 <= m, n <= 200 board[i][j] is either '.' or 'X'. Follow up: Could you do it in one-pass, using only O(1) extra memory and without modifying the values board?

Explanation

  • One-Pass Counting: Iterate through the board once. Count a battleship only when we encounter the "top-left" cell of a battleship. A cell is the top-left if it's an 'X' and either the cell above it or the cell to its left is a '.'.
    • Avoiding Overcounting: Ensure that we only count the "start" of each ship, not every 'X' cell. We can determine if an 'X' is a start by checking its neighbors above and to the left.
    • Edge Cases: Handle edge cases where the cell is on the top row or leftmost column.
  • Runtime Complexity: O(m n), where m is the number of rows and n is the number of columns. *Storage Complexity: O(1).

Code

    def countBattleships(board):
    """
    Counts the number of battleships on the board.

    Args:
        board: A list of lists of strings representing the board.

    Returns:
        The number of battleships on the board.
    """

    if not board:
        return 0

    rows = len(board)
    cols = len(board[0])
    count = 0

    for i in range(rows):
        for j in range(cols):
            if board[i][j] == 'X':
                # Check if it's the top-left cell of a battleship
                is_start = True
                if i > 0 and board[i - 1][j] == 'X':
                    is_start = False
                if j > 0 and board[i][j - 1] == 'X':
                    is_start = False

                if is_start:
                    count += 1

    return count

More from this blog

C

Chatmagic blog

2894 posts