Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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.lengthn == board[i].length1 <= m, n <= 200board[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?
Problem summary: 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).
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array
[["X",".",".","X"],[".",".",".","X"],[".",".",".","X"]]
[["."]]
number-of-islands)walls-and-gates)max-area-of-island)rotting-oranges)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #419: Battleships in a Board
class Solution {
public int countBattleships(char[][] board) {
int m = board.length, n = board[0].length;
int ans = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (board[i][j] == '.') {
continue;
}
if (i > 0 && board[i - 1][j] == 'X') {
continue;
}
if (j > 0 && board[i][j - 1] == 'X') {
continue;
}
++ans;
}
}
return ans;
}
}
// Accepted solution for LeetCode #419: Battleships in a Board
func countBattleships(board [][]byte) (ans int) {
for i, row := range board {
for j, c := range row {
if c == '.' {
continue
}
if i > 0 && board[i-1][j] == 'X' {
continue
}
if j > 0 && board[i][j-1] == 'X' {
continue
}
ans++
}
}
return
}
# Accepted solution for LeetCode #419: Battleships in a Board
class Solution:
def countBattleships(self, board: List[List[str]]) -> int:
m, n = len(board), len(board[0])
ans = 0
for i in range(m):
for j in range(n):
if board[i][j] == '.':
continue
if i > 0 and board[i - 1][j] == 'X':
continue
if j > 0 and board[i][j - 1] == 'X':
continue
ans += 1
return ans
// Accepted solution for LeetCode #419: Battleships in a Board
struct Solution;
impl Solution {
fn count_battleships(board: Vec<Vec<char>>) -> i32 {
let n = board.len();
let m = board[0].len();
let mut res = 0;
for i in 0..n {
for j in 0..m {
if Self::is_head(i, j, &board) {
res += 1;
}
}
}
res
}
fn is_head(i: usize, j: usize, board: &[Vec<char>]) -> bool {
if board[i][j] == '.' {
return false;
}
if i > 0 && board[i - 1][j] == 'X' {
return false;
}
if j > 0 && board[i][j - 1] == 'X' {
return false;
}
true
}
}
#[test]
fn test() {
let board = vec_vec_char![
['X', '.', '.', 'X'],
['.', '.', '.', 'X'],
['.', '.', '.', 'X']
];
let res = 2;
assert_eq!(Solution::count_battleships(board), res);
}
// Accepted solution for LeetCode #419: Battleships in a Board
function countBattleships(board: string[][]): number {
const m = board.length;
const n = board[0].length;
let ans = 0;
for (let i = 0; i < m; ++i) {
for (let j = 0; j < n; ++j) {
if (board[i][j] === '.') {
continue;
}
if (i && board[i - 1][j] === 'X') {
continue;
}
if (j && board[i][j - 1] === 'X') {
continue;
}
++ans;
}
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.