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 while leaving every other state unchanged.
What a phase-flip oracle does
Given a search space of N=2n items encoded as n-qubit basis states, the
oracle O acts on a superposition as
O∣ψ⟩=Ox∑αx∣x⟩=x=x∗∑αx∣x⟩−αx∗∣x∗⟩,
where x∗ is the marked item. In matrix language O is the
identity everywhere except for a −1 on the diagonal entry corresponding to
∣x∗⟩. Because it is diagonal with entries ±1, the oracle is its
own inverse: O2=I.
Building an oracle by conjugation
Suppose we want to mark ∣11⟩ in a 2-qubit space. A controlled-Z
gate does exactly that:
CZ∣11⟩=−∣11⟩,CZ∣xy⟩=∣xy⟩ for (x,y)=(1,1).
Now suppose we want to mark a different state, say ∣01⟩. The trick is
conjugation by bit-flips: wrap the CZ with X gates on any qubit that
should read 0 in the target. Flipping qubit 0 before and after temporarily
turns the condition "q0=0" into "q0=1", so the CZ fires on
∣01⟩ instead of ∣11⟩:
Any state other than ∣01⟩ picks up no net phase because the CZ never
fires on those states. The full oracle for marking ∣01⟩ is therefore
O01=(X0⊗I)CZ01(X0⊗I).
This conjugation pattern generalises to any n-bit target: apply X
gates on every qubit that is 0 in the target, apply a multi-controlled-Z,
then undo the X gates.
Try it
Implement the 2-qubit phase-flip oracle that marks ∣01⟩.
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.