The problem Grover's algorithm solves
Suppose you can recognise a solution but have no structure that tells you where to look. You have a function on inputs, of which are marked (), and the only thing you may do with is evaluate it. A classical algorithm that tries inputs in random order needs on average evaluations, and any classical algorithm needs order of them to succeed with constant probability. Grover showed that a quantum computer can find a marked input with order evaluations (Grover 1996).
Two points deserve emphasis before any mathematics. First, the speed-up is quadratic, not exponential. Second, it is a statement about the number of evaluations of , which is only a useful proxy for running time if evaluating is the expensive part. The lesson on complexity and advantage later in this course returns to what that proxy hides.
The oracle model
We assume that is available as a quantum circuit, the oracle. The most convenient form is a phase oracle,
which multiplies marked basis states by and leaves the rest alone. If you are given the more common bit oracle instead, prepare the target qubit in . Then is when and when , so the sign moves onto and the target is left unchanged. This is the phase-kickback trick you met in Foundations, in the lesson on first quantum algorithms.
In the query model we count only the uses of . Everything else (Hadamards, reflections, classical post-processing) is free. That makes lower bounds provable, which is why the model is popular, but it also means a query count is not a gate count.
The algorithm
Start in the uniform superposition and apply the Grover iteration repeatedly, where
is the diffusion operator. On amplitudes, maps each amplitude to , where is the mean amplitude: it reflects every amplitude about the mean. As a circuit, , and the middle reflection can be built from gates and a multi-controlled . The diagram shows one iteration on three qubits; the controlled is written as a Toffoli conjugated by Hadamards on its target.
After iterations, measure in the computational basis.
The geometry: a rotation in a plane
The whole analysis lives in a two-dimensional subspace. Define the normalised states
They are orthogonal, and the starting state is a combination of them:
So is the angle between and the unmarked direction . Now look at the two operators restricted to this plane.
- The oracle flips the sign of the component and keeps : within the plane it is the reflection about the line through .
- The diffusion operator keeps and flips any vector orthogonal to : it is the reflection about the line through .
Both operators map the plane to itself, so the state never leaves it. A basic fact of plane geometry finishes the argument: the product of two reflections about lines that meet at angle is a rotation by . Hence each Grover iteration rotates the state by towards , and after iterations
Measuring gives a marked item with probability
This formula is exact for every , and ; nothing has been approximated yet. Your exercise checks it against a direct simulation to ten decimal places.
Choosing the number of iterations
We want as close to as possible, so the ideal real-valued iteration count is . Two integer rules are in use.
The nearest-integer rule satisfies , so the final angle misses by at most and
This is a guarantee, with a one-line proof.
The floor rule is what most texts quote and what the KetQat SDK uses by default. It replaces by , which is accurate when , and in most cases it gives the same integer as the nearest-integer rule. It is not always the same. For and , gives ; the floor rule picks with , while the nearest-integer rule picks with . The bound sits between them. When is not small, compute exactly rather than trusting the floor rule.
Worked example: , one marked item
Here , so rad. Then , and both rules give . The success probability is , against for a single random guess. One iteration would give , and three would give : past the optimum the probability falls again. For and , exactly and one iteration lands on , so the search succeeds with certainty.
Over-rotation
Because the state keeps rotating, is periodic in with period about . Iterating twice as long as optimal rotates almost all the way back: for and , the optimum gives , while gives . "Run it longer to be safe" is exactly wrong for Grover search. If is unknown, choosing a random iteration count from a growing range still finds a marked item with an expected queries (Boyer, Brassard, Høyer and Tapp 1998); alternatively you can first estimate with phase estimation, which the phase estimation lesson prepares.
Amplitude amplification
Nothing in the geometry used the Hadamard transform specifically. Let be any circuit that prepares
where "good" means "in a subspace you can recognise with a phase oracle ". Define and
Since is the reflection about , is again a product of two reflections, and the same argument gives (Brassard, Høyer, Mosca and Tapp 2002).
The consequence is general and useful: if a procedure succeeds with probability , classical repetition needs about runs, while amplitude amplification needs about runs of and . Grover search is the special case and . The exercise asks you to check the formula with a random unitary as .
Optimality: the BBBV bound
Can a cleverer algorithm beat ? No. Bennett, Bernstein, Brassard and Vazirani proved that any quantum algorithm that finds a single marked item among with bounded error must query the oracle times (BBBV 1997). Zalka later showed that Grover's iteration count is optimal even in the constant factor (Zalka 1999).
What the theorem says: in the black-box query model, unstructured search has quantum query complexity . What it does not say: it does not say NP-complete problems need time on a quantum computer, because a real problem is not a black box; structure might be exploited by other algorithms. It is evidence, not proof, that quantum computers do not solve NP-complete problems efficiently.
The intuition behind the bound is that one query can change the state by only a small amount for most possible positions of the marked item, and you need the final states for different marked positions to be nearly orthogonal. The proof is in the paper; this course does not reproduce it.
Implementing it
A statevector implementation needs only three operations on a vector of amplitudes: a sign flip on marked indices, a reflection about the mean, and the Born rule.
import numpy as np
n, marked = 3, [5]
N = 2**n
state = np.full(N, 1 / np.sqrt(N))
for k in range(1, 4):
state[marked] *= -1 # oracle
state = 2 * state.mean() - state # diffusion: reflect about the mean
print(k, round(float(np.sum(state[marked] ** 2)), 5))
It prints 1 0.78125, 2 0.94531, 3 0.33008: the worked example above. The KetQat SDK
offers the same simulation as a catalog product that also samples seeded measurement counts
(KetQat SDK):
from ketqat_runner import catalog
record = catalog.run("[email protected]", seed=7, n_qubits=6, marked=[5], shots=1000)
print(record.result["iterations"], round(record.result["success_probability"], 6))
This prints 6 0.996586. A run writes a small record under $KETQAT_HOME (by default
~/.ketqat). The product applies the diffusion as directly, so it reports a
success probability, not a gate count; it also models no noise.
Exercise: Grover from scratch
In grover-from-scratch you implement the oracle, the diffusion operator, the iteration rules
and amplitude amplification. The checks compare your simulation with the formula
for many , compare your diffusion with its gate construction
, test the guarantee of the nearest-integer
rule for every up to nine qubits, and compare your success probabilities with the
SDK's [email protected] product.
Common mistakes
- Iterating "until it works". The success probability oscillates; past the optimum it falls. Fix the iteration count from before you run.
- Using the floor rule when is large. It can land below ; compute exactly. When , simply sampling at random already succeeds more often than not.
- Counting gates as queries. A query bound says nothing about the cost of the oracle circuit. If evaluating takes gates, every Grover iteration costs at least that much.
- Forgetting the sign of the diffusion. equals . A global sign is harmless, but if you build a controlled Grover iteration (as in amplitude estimation) the sign becomes a relative phase and matters.
- Reading BBBV as a statement about NP. It is a query lower bound for black-box search.
Summary
Grover search alternates two reflections, one about the unmarked states (the oracle) and one about the start state (diffusion). Their product rotates the state by with , so after iterations the success probability is exactly . Roughly iterations are optimal, the nearest-integer rule guarantees at least , and overshooting lowers the probability. Amplitude amplification extends the same quadratic improvement to any procedure whose success can be recognised. In the query model this is optimal, but a quadratic query advantage turns into a practical advantage only when the oracle is cheap enough, a theme the complexity and advantage lesson develops. The next lesson builds the quantum Fourier transform, the other workhorse of this module.