InterviewLegend

Battleship Game Logic & Ship Placement

Alex Chen40 min readGuide updated
In this lesson
  • Model a Battleship board, ships and game as small classes with clear jobs
  • Validate ship placement for bounds, direction and overlap before writing anything
  • Resolve a shot as miss, hit or sunk in constant time with per-ship counters
  • Run two players with turns, wasted moves and a clean game over

If you have a GitHub software engineer interview coming up, there's a fair chance one of your coding rounds is Battleship. A SWE I candidate in February 2025 was told ahead of time to expect "a battleship question and an API question." A SWE II candidate in March 2026 opened interview day with "Build a game of battleship." And a senior candidate in November 2026 got it as the second of two coding rounds, described as game logic for shooting at warships on a 2D grid, with an object-oriented design expected.

Grid size, ship lengths and fleet size change from loop to loop and are often left for you to settle, so the version here is something like what candidates describe. Expect to agree on the rules out loud. What stays constant is the shape. You build the board and ships, check placement, fire a shot and say whether it missed, hit or sank something, then handle turns and the end of the game.

The GitHub angle
Your class design gets graded along with the output. In the November 2026 senior round the interviewer expected object-oriented design and then moved on to deploying the game. Small classes with one job each, and rules enforced in one place, give you a model you can test and then talk about running online.

What the GitHub Battleship round asks

Interviewers often leave the rules loose, so expect to pin them down yourself. Spend the first few minutes on that. The classic game has ships of fixed lengths lying horizontally or vertically without overlapping. Each shot misses, hits, or hits and sinks, and you win by sinking the whole opposing fleet. Then ask about the edges, because each answer changes your code:

  • How big is the grid, and how many ships of which lengths? Are they fixed or passed in?
  • Who places the ships: the players, the program at random, or the caller as input?
  • Two players taking turns, or one player shooting at a hidden fleet?
  • What happens on a shot outside the grid, or at a cell already fired at?
  • Does a hit say which ship it hit, or is a ship named only when it sinks?

Write the answers as comments at the top of your file. When a test or a follow-up depends on one of them, you can point at it instead of arguing from memory.

Three classes cover it. A Ship knows its cells and how many of them are hit. The Board maps each occupied cell to its ship and remembers every shot, and the Game owns two boards and whose turn it is. Keep a hit count on each ship and a count of ships still afloat on each board, and sunk and game over are O(1) checks with no scan of the grid. It's the same idea as the row and column counters in LeetCode 348, Design Tic-Tac-Toe.

Board, ships and placement

Placement comes first in any version, and a lot of bugs hide there. A ship that runs off the edge, sits on another ship, or reuses a name has to be rejected before it touches the board. The class below takes the fleet one ship at a time, the way a player drags pieces onto the grid. It returns a short reason when a placement fails, so the tests can tell the failures apart.

1

Battleship Board With Ship Placement Validation

EasySignature problem
Problem
Build a Board with rows rows and cols columns. Cell (0, 0) is the top-left corner, rows grow downward and columns grow to the right.

place_ship(name, row, col, length, direction) puts a ship whose first cell is (row, col). Direction "H" runs right along the row and "V" runs down the column. It returns "placed" on success. Otherwise it returns one reason and changes nothing, checked in this order: "duplicate name", then "invalid ship" for a length below 1 or any other direction, then "out of bounds", then "overlap" when any cell already holds a ship.

ship_at(row, col) returns the name of the ship on that cell, or "" for open water.
  1. Board(5, 5)
  2. place_ship("destroyer", 0, 0, 2, "H")→ "placed"
  3. place_ship("sub", 1, 4, 3, "V")→ "placed"
  4. ship_at(0, 1)→ "destroyer"
  5. ship_at(3, 4)→ "sub"
  6. ship_at(2, 2)→ ""

The destroyer covers (0,0) and (0,1). The sub runs down column 4 from row 1 to row 3. Cell (2,2) is water.

How this uses the pattern

Compute the list of cells the ship would cover first. Check every cell against the bounds and against a dict from cell to ship name, and only write once all the checks pass.

Write it here, or go full screen with the problem, hints and solution beside the editor.

Battleship Board With Ship Placement Validation

Loading...
Click "Run" to execute your code
The GitHub angle
Recent rounds leave the grid size and fleet open, so take both as parameters and let the caller decide. That one choice also answers the "is it configurable?" question before anyone asks. The structure to name out loud is the dict from cell to ship. Every version goes on to firing shots, and that dict is what makes each shot a single lookup. Validate everything before writing anything. A ship left half placed when the overlap check fails is the classic bug in this part.
Take it further
Fleet rules. If the interviewer fixes the fleet, say one carrier of 5 and two subs of 3, add a dict of the lengths still allowed and check it in place_ship. Placing a ship takes one from its length's count, and a game can start only when every count is zero. Some versions also ban ships that touch. That's one more check over the eight neighbours of each cell, against the same dict.

Firing a shot: miss, hit or sunk

Firing is the core of the game. The November 2026 senior round was described as game logic for shooting at warships, and resolving a shot is that logic. A shot misses, hits, or sinks the ship it lands on, and the board has to know when its last ship goes down. Here one player shoots at a hidden fleet, with a Ship class carrying its own hit count.

2

Battleship Shots That Report Miss Hit or Sunk

MediumSignature problem
Problem
Extend the Board from the previous problem. place_ship works exactly as before, with the same reasons in the same order.

fire(row, col) returns "out of bounds" for a cell outside the grid and "already fired" for a cell shot before. Neither changes anything. Otherwise it records the shot and returns "miss" on water, "hit" on a ship that still has unhit cells, or "sunk " when that shot hits the ship's last unhit cell.

ships_left() returns how many placed ships aren't sunk yet.
  1. Board(5, 5)
  2. place_ship("destroyer", 0, 0, 2, "H")→ "placed"
  3. fire(0, 0)→ "hit"
  4. fire(4, 4)→ "miss"
  5. fire(0, 1)→ "sunk destroyer"
  6. ships_left()→ 0

The second hit on the two-cell destroyer sinks it, and no ships are left.

How this uses the pattern

Give each ship a hit counter and the board a count of ships afloat. A shot is a set check for repeats, one dict lookup for the ship, and a comparison of hits to length.

Write it here, or go full screen with the problem, hints and solution beside the editor.

Battleship Shots That Report Miss Hit or Sunk

Loading...
Click "Run" to execute your code
The GitHub angle
The senior report wants an object-oriented design, so put the sinking rule on the ship. A Ship that counts its own hits answers "am I sunk?" without asking the board. The board only maps cells to ships and counts what's afloat. Settle the repeat-shot rule before you code. If a second shot at a hit cell counts again, a three-cell ship can sink after two distinct hits. That bug passes most quick tests and fails the first one that repeats a shot.
Take it further
Hide the ship until it sinks. Some versions say "hit" without the name and reveal it only on "sunk", which this one already does. If the interviewer wants the name on every hit, return "hit " from the same branch. The bigger follow-up is a shot log. Keep a list of (row, col, result) on the board, and a replay or an undo becomes a walk over that list.

Two players, turns and game over

The full game puts two boards together and adds whose turn it is. Turns and game over close out the game logic, and they're where rule questions pile up. You have to decide when placement closes, whether a wasted shot costs the turn, and what a move after the game ends returns. The version here answers each one in a single place, the Game class, and leaves the board logic untouched.

3

Two-Player Battleship With Turns and Game Over

MediumFrequently asked
Problem
Build a Game for players 1 and 2, each with their own rows by cols board. place_ship(player, name, row, col, length, direction) places a ship on that player's own board with the rules and results of the first problem. It returns "invalid player" for any other player number, then "game started" once the game has started.

fire(player, row, col) shoots at the other player's board. Check in this order: "game over" once someone has won, "invalid player", then "not ready" while either board has no ships. The first shot that gets past those starts the game. Then "not your turn"; player 1 shoots first.

The shot result is the one from the previous problem. A miss, hit or sink passes the turn. "out of bounds" and "already fired" keep it. The shot that sinks the opponent's last ship returns "player wins". get_winner() returns the winner, or 0.
  1. Game(4, 4)
  2. place_ship(1, "boat", 0, 0, 2, "H")→ "placed"
  3. place_ship(2, "boat", 3, 0, 2, "H")→ "placed"
  4. fire(1, 3, 0)→ "hit"
  5. fire(1, 3, 1)→ "not your turn"
  6. fire(2, 0, 0)→ "hit"
  7. fire(1, 3, 1)→ "player 1 wins"
  8. get_winner()→ 1
  9. fire(2, 0, 1)→ "game over"

Player 1 hits, then tries again out of turn. The second player hits back, and then player 1 sinks the only ship on board 2 and wins, so the next shot is refused.

How this uses the pattern

Compose two Board objects from the previous problem, one per player. The Game only adds a turn number, a started flag and a winner, and decides which results pass the turn.

Write it here, or go full screen with the problem, hints and solution beside the editor.

Two-Player Battleship With Turns and Game Over

Loading...
Click "Run" to execute your code
The GitHub angle
Object-oriented design shows most in this part. The Game shouldn't know how a shot resolves; it asks the opponent's board and reads the answer. That keeps every rule about turns in one method you can test with no grid in your head. Name the rules you picked as you code them. Losing the turn on an off-board shot is a fair call too, and saying which one you chose and why is worth more to the interviewer than which one it is.
Take it further
A computer opponent. No GitHub report mentions one, but a bot that shoots better than at random is a natural extension if time is left. The classic approach hunts at random until it scores a hit, then targets the four neighbours of each hit cell until the ship sinks, then goes back to hunting. Keep a queue of target cells and skip any cell already fired at. Firing only at cells of one checkerboard colour while hunting halves the search, since every ship of length 2 or more covers both colours.

The senior follow-ups: running it as an online game

The November 2026 senior round didn't end at game over. After the object-oriented part, the interviewer asked about production deployment and about the performance and system issues you'd see running it online. Prepare the questions that come straight out of the code you just wrote.

Right now your Game lives in one process's memory, and production breaks that quickly. State has to survive a restart or a deploy. Two requests for the same game can land at once, and a client may retry a shot it already sent. A client must never learn where the other fleet sits either, so the server holds the only real copy of the game and sends each player their own board plus the results of their own shots. The design lesson Design Battleship as an Online Game works through storage, concurrency, idempotent moves and deploys in full.

The 2017 take-home version

Battleship isn't new at GitHub. Between February and July 2017 it was the take-home coding challenge. A March 2017 version had this spec: 3 ships on a 10 by 10 grid, with [0,0] as the bottom-left cell. Each ship is 1 cell wide and 3 long, placed vertically, and the game is created from a JSON array of each ship's topmost cell. It ran as a basic HTTP API whose responses carried one message, "hit", "miss" or "sunk".

A senior candidate that March implemented it inside a pre-made Rails app with a two-hour limit, and an April 2017 senior candidate built it as an API for playing the game and submitted it as a pull request. The format has moved to a live round since. The 2017 spec is still a useful drill, because its fixed rules strip the problem to coordinates and sinking.

4

Battleship 2017 Take-Home With Bottom-Left Coordinates

EasySometimes asked
Problem
Build a BattleshipGame on a 10 by 10 grid. Cells are (x, y) with (0, 0) at the bottom-left, so y grows upward. There are always 3 ships, each 1 cell wide and 3 cells long, standing vertically.

create(tops) takes a list of 3 [x, y] pairs, the topmost cell of each ship. A ship with top [0, 3] covers (0, 3), (0, 2) and (0, 1). It returns "invalid" if there aren't exactly 3 ships, a ship leaves the grid, or two ships share a cell. An invalid fleet leaves any current game as it was. Otherwise it starts a fresh game and returns "ok".

update(x, y) fires at a cell. It returns "invalid" before a successful create or for a cell off the grid, "miss" on water, "sunk" when all 3 cells of the ship at that cell are hit, and "hit" otherwise. Firing at a cell again never counts as a new hit.
  1. BattleshipGame()
  2. create([[0, 3], [4, 8], [6, 6]])→ "ok"
  3. update(0, 1)→ "hit"
  4. update(0, 2)→ "hit"
  5. update(5, 5)→ "miss"
  6. update(0, 3)→ "sunk"

The first ship covers (0,3), (0,2) and (0,1). Hitting all three, with a miss in between, sinks it.

How this uses the pattern

Expand each top cell into its three cells by subtracting 0, 1 and 2 from y. Map each cell to a ship index, and give each ship a set of the cells hit so far.

Write it here, or go full screen with the problem, hints and solution beside the editor.

Battleship 2017 Take-Home With Bottom-Left Coordinates

Loading...
Click "Run" to execute your code
The GitHub angle
This is the 2017 take-home spec, so treat it as history and practice. The coordinates are what trip people. With [0,0] at the bottom-left, a ship placed by its top cell grows downward toward y = 0, so the top must sit at y = 2 or higher. The 2017 spec also returns "sunk" without saying what a repeat shot does. This version keeps a set of hit cells per ship, so firing twice at one cell can't sink anything early.
Take it further
Expose it as an API. In 2017 this ran as a basic HTTP API, and one candidate built it inside a Rails app. A POST to create the game with the three tops, then a POST per shot that returns a JSON body with a message field, maps straight onto create and update. Return 400 for an invalid fleet and 404 for an unknown game, and give each game an id so several can run side by side.

What earns points in the Battleship round

GitHub doesn't publish a rubric for this round, but its shape shows what earns points. The senior round asked for object-oriented design and then for production thinking, and both reward the same habits. Pin down the rules before you code and write them where everyone can see them. Give each class one job: the ship knows its cells and hits, the board resolves shots, and the game owns turns. Keep shot resolution and game over constant-time with counters.

Test the edges as you go. A few quick calls that cover an overlap, a repeat shot, a sink and a win show the interviewer your rules hold, and they catch the half-placed ship before it costs you. Candidates generally pick their own language for GitHub's coding rounds, so use the one you can type fastest.

Common questions

Does GitHub still ask Battleship in its coding interview?

Yes. It appears at SWE I in February 2025, SWE II in March 2026 and senior in November 2026, and the SWE I candidate was told the topic beforehand. It was also the take-home in 2017. Not every loop has it. Other recent rounds include an HTTP or REST API round, a JSON query engine and a one-problem online assessment.

Is GitHub's Battleship question a LeetCode problem?

There's no LeetCode equivalent. It's an object-oriented build. The closest practice is LeetCode 348, Design Tic-Tac-Toe, which trains the same habit of keeping counters so a win check doesn't scan the board.

What grid size and fleet should I assume?

It varies, so ask. If the interviewer leaves it to you, take the grid size and the fleet as parameters and say why. The one fixed spec GitHub has used is the 2017 take-home, with 3 ships of length 3 on a 10 by 10 grid.

How should I practice it?

Build the three parts above from a blank file on a timer, testing each part before you start the next. Then rehearse the senior follow-ups out loud with the online game design lesson, since the November 2026 senior round went there right after the code.

Key Takeaways

  • ✓Battleship shows up in GitHub coding rounds at SWE I, SWE II and senior in 2025-2026. Agree the rules before coding.
  • ✓Validate the whole ship before writing any cell, using a dict from cell to ship for bounds and overlap.
  • ✓Per-ship hit counts and an afloat count make miss, hit, sunk and game over constant-time.
  • ✓Keep turn rules in the Game class, and expect senior follow-ups on running the game online.
GitHub interview guide

Know what GitHub asks before you walk in.

20 coding · 3 system design · 31 behavioral questions

Get Premium$49 a year · Instant access
Or start freeNo card.

Get their questions first.

What GitHub TestsHad your GitHub interview?How we research

InterviewLegend is independent and not affiliated with or endorsed by any company it covers.