Skip to contentSaltar al contenido
125+ QA and SEO checks per page

N-Queens Problem Implementation in Java

14 min readintermediate
Website QA and SEO audits

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 places n queens on an n×n board so that no two share a row, a column, or a diagonal, and asks for every arrangement (or one, or just the count). Because no two queens can share a row, the search restricts itself to one queen per row AND one per column, which is the same as searching over permutations of column indices, exactly why the untrimmed decision tree has n! leaves and the time bound is O(n!). Diagonal conflicts prune that tree in practice, but the bound itself comes from the permutation framing. The state that keeps space at O(n) is a single array of length n (one column per row) plus, in the fast version, three integers tracking which columns and which two diagonal families are already attacked, AND, OR and NOT on those integers test 'does this square attack a placed queen' in one instruction instead of a loop over placed queens. What differs across the eight languages below is not the algorithm but what happens at the edges of that bitmask: whether shifting past the machine word silently wraps, panics, or is simply invisible to the type checker, and whether the language even lets you write '-x' to isolate the lowest set bit.

N-Queens Problem in Java: what you actually reach for

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.

Java implementation

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. Use a private recursive helper and pass the board as int[] (a mutable reference-type array) that every call shares and mutates in place.
java
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(); // 92

Think 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 Free

The Java-specific 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. 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.

Performance in Java, beyond the O(n!)

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. The asymptotic cost is the same in every language, O(n!) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port N-Queens Problem between languages.

Real-World Applications

N-Queens Problem is used extensively in production software: database engines, compilers, operating systems, and application frameworks all use N-Queens Problem internally. In Java specifically, Spring Boot, Hibernate, and Apache libraries extensively use this approach. Understanding N-Queens Problem helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

N-Queens Problem appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose N-Queens Problem over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of N-Queens Problem to build pattern recognition. In Java, demonstrate proficiency with generics and streams API to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Java code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

If you are a student, see what GitHub Copilot offers students for free on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Want 50 audits a day? Explore SeekerPro

Engagement

0

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.