Placement Prep

Generate Binary Numbers 1 to N: Queue and Arithmetic Methods in Java

Two Java methods to generate binary numbers from 1 to N: arithmetic division and queue-BFS. Includes Java code, complexity analysis, and placement interview context.

By FACE Prep Team 4 min read
java data-structures binary-numbers queue algorithms placement-prep interview-questions

Two approaches generate binary numbers from 1 to N in Java: a modulo-arithmetic loop with no extra data structures, and a queue-based BFS that demonstrates a core traversal pattern.

Both print the same sequence for N = 5: 1, 10, 11, 100, 101. The difference is in what each implementation reveals about data structure knowledge, which is exactly what technical interviewers at product companies are probing when they ask this question.

The Arithmetic Method

The arithmetic approach converts each integer to its binary representation using repeated division by 2. For any positive integer n:

  • Divide n by 2; record the remainder (0 or 1).
  • Repeat on the quotient until n becomes 0.
  • The binary representation is the recorded remainders in reverse order.

Hand-trace for n = 5:

  • 5 % 2 = 1, quotient 2
  • 2 % 2 = 0, quotient 1
  • 1 % 2 = 1, quotient 0 — stop
  • Remainders in order: 1, 0, 1; reversed: 1, 0, 1 — result: 101
public class BinaryWithoutQueue {

    public static void main(String[] args) {
        int N = 10;
        for (int i = 1; i <= N; i++) {
            printBinary(i);
        }
    }

    public static void printBinary(int n) {
        int[] bits = new int[32];
        int index = 0;
        while (n > 0) {
            bits[index++] = n % 2;
            n = n / 2;
        }
        for (int i = index - 1; i >= 0; i--) {
            System.out.print(bits[i]);
        }
        System.out.println();
    }
}

The inner while loop runs floor(log2(n)) + 1 times for each n, so total work across all N integers is O(N log N). Space is O(log N) for the temporary bits array.

Alternative: Integer.toBinaryString()

Java’s standard library offers Integer.toBinaryString(n), which reduces the arithmetic method to a one-liner:

for (int i = 1; i <= N; i++) {
    System.out.println(Integer.toBinaryString(i));
}

This is perfectly correct. Most placement interviewers, however, will follow up by asking you to trace the manual approach. Knowing Integer.toBinaryString() without understanding why it works is a gap that shows in technical rounds.

The Queue-BFS Method

The queue approach treats binary number generation as a breadth-first search over binary strings. The binary numbering system uses base 2, with digits that can only be 0 or 1. The BFS method exploits the fact that every binary number can be constructed by appending 0 or 1 to a shorter binary number.

The algorithm:

  • Enqueue the string "1".
  • Repeat N times: dequeue the front string, print it, then enqueue two new strings (front + "0", front + "1").

The queue’s FIFO ordering guarantees that "1" is printed before "10" and "11", which are printed before "100", "101", "110", "111", and so on. No sorting is required. The level-by-level expansion is the sequence.

import java.util.LinkedList;
import java.util.Queue;

public class BinaryWithQueue {

    public static void generateBinaryNumbers(int N) {
        Queue<String> queue = new LinkedList<>();
        queue.add("1");
        for (int i = 1; i <= N; i++) {
            String binary = queue.poll();
            System.out.println(binary);
            queue.add(binary + "0");
            queue.add(binary + "1");
        }
    }

    public static void main(String[] args) {
        generateBinaryNumbers(10);
    }
}

queue.poll() retrieves and removes the front element. Each iteration enqueues two new strings and the loop terminates after exactly N dequeue operations. The strings remaining in the queue after the loop finishes are simply discarded.

The queue holds at most N + 1 entries at peak. Each string is O(log N) characters, so total space is O(N log N).

Comparing the Two Approaches

Arithmetic methodQueue-BFS method
Time complexityO(N log N)O(N log N)
Space complexityO(log N)O(N log N)
String concatenationNoneYes, O(log N) per step
Data structureFixed-size int arrayQueue<String> via LinkedList
Output orderNaturally ascendingBFS level order (same as ascending)
Interview signalBit manipulation, modulo arithmeticQueue usage, BFS ordering, FIFO discipline

The arithmetic method is more space-efficient for large N. The queue method uses more memory but communicates data structure understanding immediately, which is why interviewers at product companies tend to ask for it explicitly.

One practical note: the queue method constructs strings on every iteration. For very large N (tens of thousands), the accumulated string allocations can create noticeable GC pressure. For a placement interview with N in the range of 10 to 100, this difference is irrelevant.

Where This Problem Appears in Placement Rounds

This question appears in two distinct contexts in Indian campus recruitment.

The first context is bit-manipulation assessment. Coding rounds at IT service companies occasionally include a binary-generation problem to check whether candidates understand modulo arithmetic and binary representation. The expected output is easy to verify and the logic is short enough to write and debug in under ten minutes.

The second context is data structure assessment. Product companies and technology-focused roles use the queue variant to check whether a candidate can reason about FIFO ordering without being prompted. The question is not “can you print binary numbers” but “why does the queue produce them in order, and what does that cost in space?” That is a conceptually different probe.

Java interview questions covering collections covers Queue, List, and Map usage in the broader Java technical round context. The queue’s ordering property also connects to stack-based string problems, where data structure order replaces an explicit sort.

A useful self-check: without looking at the code, can you explain in one sentence why the queue produces binary numbers in ascending order? If yes, you are ready for the interview question. If not, trace through N = 7 manually using the queue code above.

According to GeeksforGeeks’ coverage of this problem, the queue-based approach is among the most commonly tested queue problems in placement coding rounds at Tier-2 and Tier-3 engineering colleges across India.

The BFS expansion in the queue method builds every binary string one bit at a time, level by level. That same idea, expanding structured candidates one element at a time, is at the core of how sequence models generate outputs. If you want to see how that scales from a ten-element queue to a billion-parameter language model, TinkerLLM is a hands-on LLM playground at ₹299 where you can experiment with the full generation pipeline directly.

Primary sources

Frequently asked questions

What is the time complexity of the queue method for generating binary numbers?

O(N log N) total: the loop runs N times, and each string concatenation operates on a string of O(log N) characters, giving O(N log N) overall.

Why does the queue-BFS method produce binary numbers in ascending order?

The queue follows FIFO order. Starting from '1', appending '0' gives '10' and appending '1' gives '11', exactly the next two binary numbers. Each BFS level produces the next batch in sequence automatically without any sorting.

Can I use Integer.toBinaryString() instead of writing the loop manually?

Yes, Integer.toBinaryString(n) handles this in one call. Most placement interviewers will still ask you to trace the manual approach, so understanding both methods is necessary for technical rounds.

What is the space complexity of the arithmetic method versus the queue method?

The arithmetic method uses O(log N) space for the temporary bit array. The queue method uses O(N log N) space because the queue can hold up to N strings, each of O(log N) characters.

Does this problem appear in TCS, Infosys, or other campus placement tests?

It appears in coding rounds at product companies and data structures assessments at IT majors. The queue variant specifically tests BFS understanding and data structure ordering, not just bit manipulation.

Build AI projects

A self-paced playground for building with LLMs.

TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.

Try TinkerLLM (₹299 launch)
Free AI Roadmap PDF