Count Ships on a Battle Board in One Pass Without Extra Memory
Last updated: November 29, 2026
Quick Overview
Given an m x n board where 'X' marks ship cells and '.' marks water, and ships are straight horizontal or vertical lines that never touch each other, count the ships in one pass using O(1) extra memory and without modifying the board.
0
0
0 solved
Given an m x n board where 'X' marks ship cells and '.' marks water, and ships are straight horizontal or vertical lines that never touch each other, count the ships in one pass using O(1) extra memory and without modifying the board.
A Google screen problem whose obvious answer (flood fill) is explicitly ruled out by the constraints. The interviewer is testing whether you can use the problem's structural guarantee to count each ship exactly once by its head cell.
What the Interviewer Expects
- Notes that flood fill needs a visited set or board mutation
- Counts a cell only if it is the top-left head of its ship
- Checks only the cell above and the cell to the left
- Explains why the no-touching guarantee makes this correct
- Achieves O(mn) time and O(1) space
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Ships may now touch; is O(1) memory still possible?
- Return the length of each ship.
- Validate that the board actually satisfies the no-touching rule.
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Input:
boardof'X'and'.'. - Ships are 1 x k or k x 1, separated by water on all sides (no adjacency, even diagonally irrelevant here).
- Output: number of ships.
- One pass, O(1) memory, no...
High-Level Design
Every ship has exactly one head: its top-most, left-most cell. A cell (r, c) is a head exactly when it is 'X' and neither the cell above nor the cell to the left is 'X'. Any other ship cell has ...