Mid
From PDF
Coding
C# Coding Interview
Solve N-Queens Problem?
Short answer: List<List<string>> SolveNQueens(int n) List<string> GenerateBoard(int[] board, int n)
Example code
{
List<List<string>> results = new List<List<string>>();
int[] board = new int[n]; // board[i] = column position of queen in row i Solve(0, board, results, n); return results;
} void Solve(int row, int[] board, List<List<string>> results, int n) {
if (row == n)
{ results.Add(GenerateBoard(board, n)); return;
}
for (int col = 0; col < n; col++)
{
if (IsSafe(row, col, board))
{
board[row] = col; Solve(row + 1, board, results, n); }
}
} bool IsSafe(int row, int col, int[] board) {
for (int i = 0; i < row; i++) Follow on: {
if (board[i] == col || Math.Abs(board[i] - col) == Math.Abs(i - row)) return false;
}
return true;
}
{
List<string> res = new List<string>();
for (int i = 0; i < n; i++)
{
char[] row = new char[n];
for (int j = 0; j < n; j++)
row[j] = '.';
row[board[i]] = 'Q'; res.Add(new string(row)); }
return res;
} Explanation: Backtracking places queens row by row while checking columns and diagonals.
Real-world example (ShopNest)
In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).
Say this in the interview
- Define — one clear sentence (the short answer above).
- Example — relate it to a project like ShopNest or your real work.
- Trade-off — when you would not use it.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png