Battleships in a Board
Given an $m \times n$ board where 'X's represent battleships and '.'s represent water, count the number of battleships. Battleships are placed horizontally or vertically, and are separated by water. Solve in $O(n)$ without modifying the board.
Why Interviewers Ask This
Uber interviewers use this problem to assess a candidate's ability to optimize for space complexity while maintaining algorithmic clarity. They specifically evaluate if you can identify that battleships are contiguous components and count only their unique starting points, rather than using BFS or DFS which would require O(m*n) extra space. This tests your understanding of greedy strategies and single-pass iteration constraints.
How to Answer This Question
Key Points to Cover
- Recognizing that counting ship starts avoids overcounting contiguous segments
- Explicitly addressing the O(1) space constraint by rejecting BFS/DFS
- Defining the precise condition for a cell being a ship's head
- Handling boundary checks for the top row and leftmost column safely
- Demonstrating clear communication of time and space complexity trade-offs
Sample Answer
Common Mistakes to Avoid
- Using a visited array or recursion stack which violates the O(1) space requirement
- Iterating through the board twice or using complex data structures unnecessarily
- Failing to check both the top and left neighbors, leading to incorrect counts
- Attempting to mark visited cells by modifying the input board directly
Practice This Question with AI
Answer this question orally or via text and get instant AI-powered feedback on your response quality, structure, and delivery.