|q⟩ Bad Qubits

intermediate · Programming · Grover's Search Algorithm

The Search Oracle

Grover's algorithm needs two ingredients: an oracle and a diffuser. The oracle is the piece that "knows" the answer — it marks the target item by giving it a phase of 1-1 while leaving every other state unchanged.

What a phase-flip oracle does

Given a search space of N=2nN = 2^n items encoded as nn-qubit basis states, the oracle O\mathcal{O} acts on a superposition as

Oψ=Oxαxx=xxαxxαxx,\mathcal{O}\,|\psi\rangle = \mathcal{O}\sum_x \alpha_x |x\rangle = \sum_{x \neq x^*} \alpha_x |x\rangle - \alpha_{x^*} |x^*\rangle,

where xx^* is the marked item. In matrix language O\mathcal{O} is the identity everywhere except for a 1-1 on the diagonal entry corresponding to x|x^*\rangle. Because it is diagonal with entries ±1\pm 1, the oracle is its own inverse: O2=I\mathcal{O}^2 = I.

Building an oracle by conjugation

Suppose we want to mark 11|11\rangle in a 2-qubit space. A controlled-ZZ gate does exactly that:

CZ11=11,CZxy=xy for (x,y)(1,1).CZ\,|11\rangle = -|11\rangle, \qquad CZ\,|xy\rangle = |xy\rangle \text{ for } (x,y) \neq (1,1).

Now suppose we want to mark a different state, say 01|01\rangle. The trick is conjugation by bit-flips: wrap the CZ with XX gates on any qubit that should read 00 in the target. Flipping qubit 0 before and after temporarily turns the condition "q0=0q_0 = 0" into "q0=1q_0 = 1", so the CZ fires on 01|01\rangle instead of 11|11\rangle:

(X0I1)  CZ  (X0I1)  01=(X0I1)  CZ  11=(X0I1)  11=01.(X_0 \otimes I_1)\; CZ\; (X_0 \otimes I_1)\;|01\rangle = (X_0 \otimes I_1)\; CZ\;|11\rangle = -(X_0 \otimes I_1)\;|11\rangle = -|01\rangle.

Any state other than 01|01\rangle picks up no net phase because the CZ never fires on those states. The full oracle for marking 01|01\rangle is therefore

O01=(X0I)  CZ01  (X0I).\mathcal{O}_{01} = (X_0 \otimes I)\; CZ_{01}\; (X_0 \otimes I).

This conjugation pattern generalises to any nn-bit target: apply XX gates on every qubit that is 00 in the target, apply a multi-controlled-ZZ, then undo the XX gates.

Try it

Implement the 2-qubit phase-flip oracle that marks 01|01\rangle. The grader checks the complete unitary matrix of your circuit — doing nothing, or flipping the wrong state, will not pass.

Run your code to see the quantum state.

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