|q⟩ Bad Qubits

beginner · Programming · First Quantum Algorithms: Deutsch & Deutsch–Jozsa

Building the DJ Oracle

You have seen how the Deutsch–Jozsa algorithm uses a single oracle query to decide whether a Boolean function is constant or balanced. The algorithm works regardless of how the oracle is built — but at some point you have to build one. This lesson shows how to translate a concrete balanced function into a circuit that a quantum computer can execute.

What the oracle must do

Recall the standard oracle construction. Given a function f:{0,1}n{0,1}f : \{0,1\}^n \to \{0,1\}, the oracle unitary UfU_f acts on an nn-qubit input register and a 1-qubit ancilla register:

Ufxy=xyf(x),U_f \,|x\rangle|y\rangle = |x\rangle|y \oplus f(x)\rangle,

where \oplus denotes addition modulo 2 (XOR). The input x|x\rangle is left untouched; the function value f(x)f(x) is XOR-ed into the ancilla y|y\rangle. Applying UfU_f twice returns the original state, confirming that the mapping is reversible.

The XOR function on two input bits

For the Deutsch–Jozsa problem with n=2n = 2 input bits, the oracle acts on 3 qubits altogether: qubits 0 and 1 form the input register, and qubit 2 is the ancilla. A convenient balanced function to use as an example is

f(x0,x1)=x0x1.f(x_0, x_1) = x_0 \oplus x_1.

You can verify it is balanced by enumeration: the four possible inputs give outputs f(00)=0f(00)=0, f(01)=1f(01)=1, f(10)=1f(10)=1, f(11)=0f(11)=0 — exactly two zeros and two ones, confirming the definition of a balanced function.

The oracle for this function must implement

Ufx0,x1,y=x0,x1,  yx0x1.U_f \,|x_0, x_1, y\rangle = |x_0, x_1,\; y \oplus x_0 \oplus x_1\rangle.

Building the oracle from CNOT gates

The CNOT gate does exactly one thing: it XOR-flips the target qubit conditioned on the control qubit. Formally, CNOTctxc,xt=xc,xtxc\text{CNOT}_{c \to t}\,|x_c, x_t\rangle = |x_c, x_t \oplus x_c\rangle.

To build UfU_f for f=x0x1f = x_0 \oplus x_1 we need qubit 2 to accumulate both x0x_0 and x1x_1 via XOR. Two CNOTs suffice, applied in sequence:

  1. CNOT02\text{CNOT}_{0 \to 2}: sends qubit 2 from yy to yx0y \oplus x_0.
  2. CNOT12\text{CNOT}_{1 \to 2}: sends qubit 2 from yx0y \oplus x_0 to yx0x1y \oplus x_0 \oplus x_1.

After both gates the ancilla holds yf(x0,x1)y \oplus f(x_0, x_1), which is exactly what the oracle specification demands. The two input qubits are unchanged throughout.

Try it

Implement the oracle for f(x0,x1)=x0x1f(x_0, x_1) = x_0 \oplus x_1 on a 3-qubit circuit. The grader checks the full unitary matrix, so leaving the circuit empty will not pass — you must add the two CNOT gates that write the function value into the ancilla.

Run your code to see the quantum state.

Sign in on the full site to ask questions and join the discussion.