So far you have seen Grover's algorithm with exactly one marked item. The algorithm generalises to
M marked items, and understanding that generalisation reveals why Grover is fast and how fewer
iterations are needed when more solutions exist.
Geometry with M solutions
Grover's algorithm is best understood geometrically. Let N=2n be the total number of basis
states and M the number of marked items. Define two unit vectors:
∣W⟩=M1∑x∈marked∣x⟩,∣W⊥⟩=N−M1∑x∈/marked∣x⟩.
The initial uniform superposition ∣s⟩=H⊗n∣0⟩⊗n lies in the
plane spanned by ∣W⟩ and ∣W⊥⟩:
∣s⟩=NM∣W⟩+NN−M∣W⊥⟩.
The angle θ between ∣s⟩ and ∣W⊥⟩ satisfies sinθ=M/N.
Each Grover iteration is a rotation by 2θ toward ∣W⟩. After k iterations the total
probability of measuring any marked item is
Pmarked(k)=sin2((2k+1)θ).
The optimal number of iterations
Setting Pmarked=1 requires (2k+1)θ=π/2, giving
k∗=2θπ/2−θ=4θπ−21.
For small θ this is approximately π/(4θ)≈4πN/M.
A special case: exact certainty
For N=8 (three qubits) and M=2, we get sinθ=2/8=1/2, so θ=π/6.
The optimal number of iterations is
k∗=2⋅π/6π/2−π/6=π/3π/3=1.
Exactly one iteration, and the success probability is sin2(3⋅π/6)=sin2(π/2)=1.
This is not an approximation: the geometry works out perfectly for M=2 in an 8-element space.
The multi-target oracle
When the oracle must mark multiple states {x1,x2,…,xM}, you simply compose the
individual phase-flip unitaries:
Uf=UxM⋯Ux2⋅Ux1
where Uxi phase-flips only ∣xi⟩. The diffuser stays unchanged — it reflects about
the uniform superposition ∣s⟩ regardless of how many items the oracle marks.
Each single-target oracle is built with the same pattern you already know: apply X gates to every
qubit that should be ∣0⟩ in the target bitstring (converting the target to all-ones), then
apply an n-qubit controlled-Z, then undo the X gates. The n-qubit controlled-Z is
realised without ancilla qubits by the identity
Cn−1Z=Hn−1⋅Cn−1X⋅Hn−1,
i.e., sandwich a Toffoli (or its multi-controlled generalisation) between Hadamards on the last
qubit. For three qubits this is H(2),CCX(0,1,2),H(2).
Try it
The exercise targets N=8 states with M=2 marked items: ∣000⟩ and ∣111⟩.
Complete the two oracle phase-flips; the diffuser is already provided. The grader checks the output
distribution, which should place equal probability on ∣000⟩ and ∣111⟩ and zero on
all other states.
Run your code to see the quantum state.
Sign in on the full site to ask questions and join the discussion.