Hello LeetCode Community! 👋
I recently went through an exciting onsite interview experience with IBM for the Software Development Engineer II (SDE2) position. Today, I'd like to share my journey, particularly how I tackled the classic "N-Queens" problem. This challenge assesses your problem-solving skills and ability to implement an efficient solution.
Interview Details:
Problem Statement:
Given an integer 'n', return all distinct solutions to the 'n'-queens puzzle. You are required to place 'n' queens on an 'n x n' chessboard, ensuring that no two queens threaten each other.
Example:
For 'n = 4', there are two distinct solutions.
Solution 1:
[".Q..",
"...Q",
"Q...",
"..Q."]
Solution 2:
["..Q.",
"Q...",
"...Q",
".Q.."]Code:
Here's my Python solution to the N-Queens problem:
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
if n == 0:
return []
def bt(r):
if r == n:
result.append(op[:])
for c in range(n):
if c in col or r+c in dig or r-c in adig:
continue
col.add(c)
dig.add(r+c)
adig.add(r-c)
op.append('.'*c+'Q'+'.'*(n-c-1))
bt(r+1)
col.remove(c)
dig.remove(r+c)
adig.remove(r-c)
op.pop()
col, dig, adig, op, result = set(), set(), set(), [], []
bt(0)
return resultMain Discussion:
During the interview, I began by explaining my thought process before delving into the code. I opted for a backtracking approach to solve the N-Queens problem. This method explores all possible placements of queens on the chessboard, ensuring no two queens threaten each other. By employing backtracking, we efficiently explore all solutions without redundancies.
I encourage fellow candidates preparing for IBM interviews to share their experiences, alternative solutions, or any additional insights into the N-Queens problem. Let's build a helpful resource for the LeetCode community. Remember to format your code using three backticks (```) for clarity, and include diverse examples to illustrate your solutions effectively!
Wishing everyone the best in their interview preparations, and happy coding! 🚀✨ #NQueensProblem
Warm regards,
Vignesh