Battleships in a Board

MediumMatrixsimulation

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given an m x n board where each cell is either 'X' (part of a battleship) or '.' (empty). Every battleship is a straight horizontal or vertical line of 'X' cells, of length 1 or more. The board is guaranteed to be valid: no two different battleships touch each other horizontally or vertically (there is always at least one empty cell between them along those directions). Return the number of battleships on the board. Follow-up worth discussing: can you solve it in one pass, using O(1) extra memory and without modifying the board?

Examples

Input: board = [["X",".",".","X"],[".",".",".","X"],[".",".",".","X"]]
Output: 2
There is a single-cell ship at the top-left and a vertical ship of length 3 in the last column.
Input: board = [["."]]
Output: 0
The board is empty.

Constraints

  • 1 <= m, n <= 200
  • `board[i][j]` is `'X'` or `'.'`
  • The board is a valid arrangement of battleships

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More simulation problems