N-Queens Problem Implementation in Java
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn your Backtracking question into a ready to paste AI prompt, free →
Key Takeaways
- ✓N-Queens Problem runs in O(n!) time and O(n) space, in Java as in every other language.
- ✓java.lang.Integer supplies the intrinsics: Integer.bitCount(x), Integer.numberOfTrailingZeros(x) and Integer.numberOfLeadingZeros(x) operate on the 32-bit int the JVM already uses natively, and HotSpot recognizes all three and compiles them to a single POPCNT/BSF hardware instruction once the method is JIT-compiled, rather than calling into library code.
- ✓Track cols/diag1/diag2 as plain int parameters and use the same AND/OR/NOT/shift expressions a C programmer would; Java's overflow behavior is defined by the JLS as silent two's-complement wraparound with no exception, so no keyword or build-mode flag changes it the way Rust's does.
- ✓The Java trap: The board array is a reference type, so results.add(board) after a solution completes does NOT save a snapshot, it stores a reference to the SAME array every future call keeps mutating, and by the time the search finishes every entry in results silently points at the identical final board.
- ✓The n! decision-tree bound is identical to every language here, but Java pays a JIT warm-up tax the others don't: Integer.bitCount/numberOfTrailingZeros only compile down to the hardware instruction after HotSpot has profiled the method as hot, so a cold JVM run measures noticeably slower than the steady-state number a long-running server would see.
What N-Queens Problem actually is
N-Queens Problem in Java: what you actually reach for
Java implementation
import java.util.ArrayList;
import java.util.List;
public final class NQueens {
public static List<int[]> solve(int n) {
List<int[]> solutions = new ArrayList<>();
int full = (1 << n) - 1;
int[] board = new int[n];
place(0, n, full, 0, 0, 0, board, solutions);
return solutions;
}
private static void place(int row, int n, int full, int cols, int diag1, int diag2,
int[] board, List<int[]> solutions) {
if (row == n) {
solutions.add(board.clone()); // without clone(), every entry aliases `board`
return;
}
int available = full & ~(cols | diag1 | diag2);
while (available != 0) {
int pos = available & -available;
available -= pos;
board[row] = Integer.numberOfTrailingZeros(pos);
place(row + 1, n, full, cols | pos, (diag1 | pos) << 1, (diag2 | pos) >>> 1, board, solutions);
}
}
}
// int count = NQueens.solve(8).size(); // 92Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Java-specific trap
Performance in Java, beyond the O(n!)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Java type or library should I use for N-Queens Problem?
java.lang.Integer supplies the intrinsics: Integer.bitCount(x), Integer.numberOfTrailingZeros(x) and Integer.numberOfLeadingZeros(x) operate on the 32-bit int the JVM already uses natively, and HotSpot recognizes all three and compiles them to a single POPCNT/BSF hardware instruction once the method is JIT-compiled, rather than calling into library code.
What is the most common Java mistake when implementing N-Queens Problem?
The board array is a reference type, so results.add(board) after a solution completes does NOT save a snapshot, it stores a reference to the SAME array every future call keeps mutating, and by the time the search finishes every entry in results silently points at the identical final board. You must results.add(board.clone()) (or Arrays.copyOf); forgetting this is one of the single most common correctness bugs in Java backtracking code, and it produces no compiler warning and no exception, only wrong output.
How does N-Queens Problem actually perform in Java?
The n! decision-tree bound is identical to every language here, but Java pays a JIT warm-up tax the others don't: Integer.bitCount/numberOfTrailingZeros only compile down to the hardware instruction after HotSpot has profiled the method as hot, so a cold JVM run measures noticeably slower than the steady-state number a long-running server would see. int[] is a genuinely unboxed primitive array in Java, so mutate-in-place backtracking on int[] board never touches an object header or boxing machinery the way List<Integer> would. Time complexity is O(n!) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what GitHub Copilot offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.