Skip to problem
←

N-Queens

Hard 0 attempts

Arrange n queens on an n x n chessboard so that none of them attack one another — meaning no two queens may share a row, a column, or a diagonal. Return every distinct board arrangement that satisfies this.

Each returned solution is an array of strings, where 'Q' denotes a square holding a queen and '.' denotes an empty one.

Place exactly n queens. Return each board once; rotations and reflections count as different arrangements when their row strings differ. The order of boards does not matter, but rows within each board must remain top to bottom. If no arrangement exists, return [].

Function contract

Implement solveNQueens(n). Receive the board size and the exact number of queens to place.

Output: Return every distinct valid board exactly once, in any outer order. Each board contains n row strings of length n using Q and .; row order is significant. Return [] if no arrangement exists.

Example 1

Input
n = 4
Output
[[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]

Example 2

Input
n = 1
Output
[["Q"]]
Visual Aid
A valid board for n = 4
Valid four-queen board with columns 1, 3, 0, 2 from top to bottomQQQQOne queen per row.One queen per column.No shared diagonal.One of two solutions.

Rows are .Q.., ...Q, Q..., and ..Q. No pair of queens shares a row, column, or diagonal.

Constraints
  • 1 <= n <= 9

Place queens one row at a time using backtracking. Track which columns and diagonals are already attacked using sets. A queen at (row, col) occupies the row - col diagonal and the row + col anti-diagonal.

javascript
function solveNQueens(n) {
  const result = [];
  const cols = new Set();
  const diag = new Set();
  const antiDiag = new Set();
  const board = Array.from({ length: n }, () => '.'.repeat(n));

  function backtrack(row) {
    if (row === n) {
      result.push([...board]);
      return;
    }
    for (let col = 0; col < n; col++) {
      if (cols.has(col) || diag.has(row - col) || antiDiag.has(row + col)) continue;

      cols.add(col);
      diag.add(row - col);
      antiDiag.add(row + col);
      board[row] = board[row].substring(0, col) + 'Q' + board[row].substring(col + 1);

      backtrack(row + 1);

      cols.delete(col);
      diag.delete(row - col);
      antiDiag.delete(row + col);
      board[row] = '.'.repeat(n);
    }
  }

  backtrack(0);
  return result;
}

Time: O(n² × n!) as a loose upper bound including candidate checks and board-string construction. Space: O(n²) for the current board strings, plus O(n) for sets and recursion, excluding returned boards.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript