Working Through the First Lady Of Software Hackerrank Problem
I keep running into people who get tripped up on this one during virtual assessment rounds. The problem statement on HackerRank is phrased as placing "queens" (or sometimes re-skinned as placing software engineers in an office grid) such that no two share a row, column, or diagonal. It's the N-Queens problem wearing a different shirt. The core approach is backtracking with column and diagonal tracking, and most candidates either overcomplicate it or miss a key edge case with the diagonals. Here is how you actually solve it. You place one queen per row, recursively trying each column position and checking whether that square is under attack. The naive check — scanning every previously placed queen to compare positions — works for small N but tanks your runtime when HackerRank runs hidden test cases with N = 12 or higher. The trick is using sets to track occupied columns and diagonals in O(1) time instead of O(n). The two diagonal identifiers are what people mess up. For any cell at row r and column c, the sum r + c is constant along one diagonal (top-left to bottom-right), and the difference r - c is constant along the other (top-right to bottom-left). Those sums and differences never change no matter where you are on the board. So you maintain three sets: cols for occupied columns, diag1 for occupied r+c values, and diag2 for occupied r-c values. If any of those contain your target position, skip it.
When you recurse to the next row, add the current position to all three sets before diving deeper. When you backtrack after that recursive call returns, remove the position from the sets so sibling branches get a clean slate. If you reach row N, you have found a valid configuration and you can count it or print it depending on what the problem asks for. Here is a clean Python implementation that should pass the standard test suite:
def total_n_queens(n):
def backtrack(row):
if row == n:
result[0] += 1
return
for col in range(n):
if col in cols or (row + col) in diag1 or (row - col) in diag2:
continue
cols.add(col)
diag1.add(row + col)
diag2.add(row - col)
backtrack(row + 1)
cols.remove(col)
diag1.remove(row + col)
diag2.remove(row - col)
result = [0]
cols = set()
diag1 = set()
diag2 = set()
backtrack(0)
return result[0]
I learned the hard way that you need to be careful about one thing that is not obvious from reading the problem once. HackerRank sometimes includes test cases where N = 0 or N = 1 as boundary inputs, and some versions of this problem ask you to return all distinct board configurations rather than just the count. My first submission that used a simple counter failed because the hidden tests checked for N = 0 returning an empty list rather than 1. Make sure you read the output specification carefully. If the problem asks for all solutions, collect the boards in a list instead of incrementing a counter, and format each board as a list of strings with "Q" for queens and "." for empty spaces. Another thing that catches people off guard is recursion depth. For N = 14 on some platforms, the default Python recursion limit becomes a real problem. I ran into this during a mock interview when my solution hung on the largest test case. The fix is simply calling sys.setrecursionlimit(3000) at the top of your script, or switching to an iterative backtracking approach. I prefer the iterative version for anything above N = 13 because it makes debugging easier and avoids stack overflow errors on strict judges.
Get the Full Details

Pitfalls and Where This Approach Breaks Down
The backtracking with sets approach runs in O(N!) worst case time and O(N) space. That is fine for N up to about 15 on most online judges. Beyond that, you are looking at minutes of runtime even with the set optimization, and HackerRank will time you out. There is no known polynomial-time algorithm for counting all N-Queens solutions — the sequence is well studied and grows super-exponentially. If you see a version of this problem with N > 15 and expect a fast solution, something is wrong with the problem statement or you need a precomputed lookup table, which is basically cheating but sometimes the only viable path in a timed contest. Bitmask backtracking is a significant optimization for N up to around 20. Instead of using Python sets, you represent column and diagonal occupancy as integers and use bitwise OR and AND operations to check and update state. This cuts runtime by roughly 5 to 10x in practice because integer operations are much faster than hash set operations in most languages. The tradeoff is that the code looks less readable and you need to handle the diagonal shifts carefully since they move one bit position per row. In C++ or Java, bitmask is almost always the right choice. In Python, the built-in integer operations help but the interpreter overhead means the gain is smaller than in lower-level languages. I also want to flag a common misconception. Some candidates try to generate all permutations of column indices and then filter out the ones with diagonal conflicts. That is technically correct but dramatically slower because it explores N! arrangements upfront before checking any constraints. Backtracking with constraint pruning eliminates entire subtrees as soon as a conflict is detected, which for N = 8 reduces the search space from 40,320 permutations to 92 valid solutions with far fewer nodes visited. The difference is not subtle — permutation generation will TLE on anything larger than N = 9.
Final Notes on Submission Strategy
Before you hit submit, run through the sample cases manually. Verify N = 4 gives 2 solutions, N = 8 gives 92, and N = 1 gives 1. These are the standard reference values and they should match exactly. If your count for N = 8 is 91 or 93, you have a bug in your diagonal logic or you are double-counting symmetric configurations when the problem does not want you to. Also check whether the problem asks for the count of unique solutions or all solutions including rotations and reflections — the standard HackerRank version wants the basic count of distinct placements, not the reduced set under symmetry.