The naive approach is easy enough, just DFS or BFS and mark visited cells.
Clarify that since battleships are not adjacent, each ship can be identified by its top-left cell (or leftmost/topmost cell). Scan the grid and count a cell as a new ship only if it is 'X' and has no 'X' above or to the left. This gives O(m*n) time and O(1) space without modifying the board.
Pro tip: Explicitly state the non-adjacency guarantee and how it simplifies the problem; interviewers at Meta value candidates who leverage constraints to avoid unnecessary complexity like DFS or union-find.
Confirm that ships are 1xk or kx1, non-adjacent (no touching even diagonally), and that the board cannot be modified. Discuss empty grid, single cell, and all empty cases.
Because ships are non-adjacent, each ship has exactly one cell that is the topmost and leftmost (i.e., no 'X' above or to the left). Counting these cells counts ships.
Iterate through each cell. If grid[i][j] == 'X' and (i == 0 or grid[i-1][j] != 'X') and (j == 0 or grid[i][j-1] != 'X'), increment count. This is O(m*n) time and O(1) extra space.
State time O(m*n) and space O(1). Address the follow-up by emphasizing no board modification and constant space. Mention that the solution naturally satisfies the follow-up.
Walk through a small example (e.g., 2x2 with one ship) to verify correctness, and consider edge cases like a ship at the border.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.