The Deutsch-Jozsa algorithm solves a problem that classically requires up to 2^(n−1)+1 queries: given a black-box function f:ⁿ→, determine whether it is constant (same output for all inputs) or balanced (outputs 0 for exactly half the inputs and 1 for the other half). The quantum algorithm answers with certainty using just one query to the oracle. This is one of the earliest examples of an exponential separation between classical and quantum query complexity.Documentation Index
Fetch the complete documentation index at: https://mintlify.com/itsubaki/qasm-playground/llms.txt
Use this file to discover all available pages before exploring further.
Code
- Constant oracle
- Balanced oracle
Step-by-step explanation
Gate definitionsx(Pauli-X / NOT):U(pi, 0, pi)— flips |0⟩ ↔ |1⟩.h(Hadamard):U(pi/2, 0, pi)— creates superposition.cx(CNOT): controlledU(pi, 0, pi)— used inside the balanced oracle.
oracle function differs:
constant(q0, q1)appliesx q1, which flips the ancilla unconditionally. This implements f(x) = 1 for all x — a constant function.balanced(q0, q1)appliescx q0, q1, which flips the ancilla only when q0 is |1⟩. This implements f(x) = x — a balanced function that outputs 0 and 1 for equal numbers of inputs.
reset. The ancilla qubit q1 is prepared in the |−⟩ state:
- Constant function: The ancilla flips regardless of q0. The phase factor (−1)^f(x) is the same for both terms in q0’s superposition, introducing a global phase that does not affect the measurement.
- Balanced function: The CNOT ties the ancilla flip to q0’s value. The relative phase between |0⟩ and |1⟩ in q0’s superposition flips sign, turning (|0⟩ + |1⟩)/√2 into (|0⟩ − |1⟩)/√2.
h q0 maps back from the Hadamard basis:
- If the oracle was constant: q0 → |0⟩
- If the oracle was balanced: q0 → |1⟩
Expected output
Measuring q0 after the final Hadamard gives a deterministic result:| Oracle type | Measurement of q0 |
|---|---|
| Constant | 0 (100%) |
| Balanced | 1 (100%) |
To switch between oracles, only the body of
oracle changes — constant(q0, q1) vs balanced(q0, q1). The surrounding circuit structure (initialization, final Hadamard) is identical in both cases.