Grover's algorithm
De Seitn is no ned ibersetzt worn. Sie schaung de englische Originalversion o.
For this Qiskit in Classrooms module, students must have a working Python environment with the following packages installed:
qiskitv2.1.0 or newerqiskit-ibm-runtimev0.40.1 or newerqiskit-aerv0.17.0 or newerqiskit.visualizationnumpypylatexenc
To set up and install the packages above, see the Install Qiskit guide. In order to run jobs on real quantum computers, students will need to set up an account with IBM Quantum® by following the steps in the Set up your IBM Cloud account guide.
This module was tested and used 12 seconds of QPU time. This is a good-faith estimate; your actual usage may vary.
# Added by doQumentation — required packages for this notebook
!pip install -q qiskit qiskit-ibm-runtime
# Uncomment and modify this line as needed to install dependencies
#!pip install 'qiskit>=2.1.0' 'qiskit-ibm-runtime>=0.40.1' 'qiskit-aer>=0.17.0' 'numpy' 'pylatexenc'
Introduction
Grover's algorithm is a foundational quantum algorithm that addresses the unstructured search problem: given a set of items and a way to check if any given item is the one you're looking for, how quickly can you find the desired item? In classical computing, if the data is unsorted and there is no structure to exploit, the best approach is to check each item one by one, leading to a query complexity of — on average, you'll need to check about half the items before finding the target.

Grover's algorithm, introduced by Lov Grover in 1996, demonstrates how a quantum computer can solve this problem much more efficiently, requiring only steps to find the marked item with high probability. This represents a quadratic speedup over classical methods, which is significant for large datasets.
The algorithm operates in the following context:
- Problem setup: You have a function that returns 1 if is the item you want, and 0 otherwise. This function is often called an oracle or black box, since you can only learn about the data by querying .
- Usefulness of quantum: While classical algorithms for this problem require, on average, queries, Grover's algorithm can find the solution in roughly queries, which is much faster for large .
- How it works (at a high level):
- The quantum computer first creates a superposition of all possible states, representing all possible items at once.
- It then repeatedly applies a sequence of quantum operations (the Grover iteration) that amplifies the probability of the correct answer and diminishes the others.
- After enough iterations, measuring the quantum state yields the correct answer with high probability.
Here is a very basic diagram of Grover's algorithm that skips over a lot of nuance. For a more detailed diagram, see this paper.

A few things to note about Grover's algorithm:
- It is optimal for unstructured search: no quantum algorithm can solve the problem with fewer than queries.
- It provides only a quadratic, not exponential, speedup — unlike some other quantum algorithms (for example, Shor's algorithm for factoring).
- It has practical implications, such as potentially speeding up brute-force attacks on cryptographic systems, though the speedup is not enough to break most modern encryption by itself.
For undergraduate students familiar with basic computing concepts and query models, Grover's algorithm offers a clear illustration of how quantum computing can outperform classical approaches for certain problems, even when the improvement is "only" quadratic. It also serves as a gateway to understanding more advanced quantum algorithms and the broader potential of quantum computing.
Amplitude amplification is a general purpose quantum algorithm, or subroutine, that can be used to obtain a quadratic speedup over a handful of classical algorithms. Grover’s algorithm was the first to demonstrate this speedup on unstructured search problems. Formulating a Grover's search problem requires an oracle function that marks one or more computational basis states as the states we are interested in finding, and an amplification circuit that increases the amplitude of marked states, consequently suppressing the remaining states.
Here, we demonstrate how to construct Grover oracles and use the GroverOperator from the Qiskit circuit library to easily set up a Grover's search instance. The runtime Sampler primitive allows seamless execution of Grover circuits.
Math
Suppose there exists a function that maps binary strings to a single binary variable, meaning
One example defined on is
Another example defined on is
You are tasked with finding quantum states corresponding to those arguments of that are mapped to 1. In other words, find all such that (or if there is no solution, report that). We would refer to non-solutions as . Of course, we will do this on a quantum computer, using quantum states, so it is useful to express these binary strings as states:
Using the quantum state (Dirac) notation, we are looking for one or more special states in a set of possible states, where is the number of qubits, and with non-solutions denoted
We can think of the function as being provided by an oracle: a black-box that we can query to determine its effect on a state In practice, we will often know the function, but it may be very complicated to implement, meaning that reducing the number of queries or applications of could be important. Alternatively, we can imagine a paradigm in which one person is querying an oracle controlled by another person, such that we don't know the oracle function, we only know its action on particular states from querying.
This is an "unstructured search problem, in that there is nothing special about that aids us in our search. The outputs are not sorted nor are solutions known to cluster, and so on. Consider use old, paper phone books as an analogy. This unstructured search would be like scanning through it looking for a certain number, and not like looking through an alphabetized list of names.
In the case where a single solution is sought, classically, this requires a number of queries that is linear in . Clearly you might find a solution on the first try, or you might find no solutions in the first guesses, such that you need to query the input to see if there is any solution at all. Since the functions have no exploitable structure, you will require guesses on average. Grover's algorithm requires a number of queries or computations of that scales like
Sketch of circuits in Grover's algorithm
A full mathematical walkthrough of Grover's algorithm can be found, for example, in Fundamentals of quantum algorithms, a course by John Watrous on IBM Quantum Learning. A condensed treatment is provided in an appendix at the end of this module. But for now, we will only review the overall structure of the quantum circuit that implements Grover's algorithm.
Grover's algorithm can be broken down into the following stages:
- Preparation of an initial superposition (applying Hadamard gates to all qubits)
- "Marking" the target state(s) with a phase flip
- A "diffusion" stage in which Hadamard gates and a phase flip are applied to all qubits.
- Possible repetitions of the marking and diffusion stages to maximize the probability of measuring the target state
- Measurement
Often, the marking gate and the diffusion layers consisting of and are collectively referred to as the "Grover operator". In this diagram, only a single repetition of the Grover operator is shown.
Hadamard gates are well-known and used widely throughout quantum computing. The Hadamard gate creates superposition states. Specifically it is defined by
Its operation on any other state is defined through linearity. In particularly, a layer of Hadamard gates allows us to go from the initial state with all qubits in (denoted ) to a state where each qubit has some probability of being measured in either or this lets us probe the space of all possible states differently from in classical computing.
An important corollary property of the Hadamard gate is that acting a second time can undo such superposition states:
This will be important in just a moment.
Check your understanding
Read the question below, think about your answer, then click the triangle to reveal the solution.
Starting from the definition of the Hadamard gate, demonstrate that a second application of the Hadamard gate undoes such superpositions as claimed above.
Answer:
When we apply X to the state, we get the value and +1 and to the state we get -1, so if we had a 50-50 distribution, we would get an expectation value of 0.
The gate is less common, and is defined according to
Finally, the gate is defined by
Note the effect of this is that flips the sign on a target state for which and leaves other states unaffected.
At a very high, abstract level you can think about the steps in the circuit in the following ways:
- First Hadamard layer: puts the qubits into a superposition of all possible states.
- : mark the target state(s) by adding a "-" sign in front. This doesn't immediately change measurement probabilities, but it changes how the target state will behave in subsequent steps.
- Another Hadamard layer: The "-" sign introduced in the previous step will change the relative sign between some terms. Since Hadamard gates turn one mixture of computational states into one computational state, and they turn into this relative sign difference can now begin to play a role in what states are measured.
- One final layer of Hadamard gates is applied, and then measurements are made. We will see in more detail how this works in the next section.
Example
To better understand how Grover's algorithm works, let us work through a small, two-qubit example. This may be considered optional for those not focused on quantum mechanics and Dirac notation. But for those who hope to work substantially with quantum computers, this is highly recommended.
Here is the circuit diagram with the quantum states labeled at various positions throughout. Note that with only two qubits, there are only four possible states that could be measured under any circumstances: , , , and .

Let us suppose that the oracle (, unknown to us) marks the state . We will work through the actions of each set of quantum gates, including the oracle, and see what distribution of possible states come out at the time of measurement. At the very beginning, we have
Using the definition of Hadamard gates, we have
Now the oracle marks the target state:
Note that in this state, all four possible outcomes have the same probability of being measured. They all have a weight of magnitude meaning they each have a chance of being measured. So while the state is marked through the "-" phase, this has not yet resulted in any increased probability of measuring that state. We continue by applying the next layer of Hadamard gates.
Combining like terms, we find
Now flips the sign on all states but :
And finally, we apply the last layer of Hadamard gates:
It is worth working through the combining of these terms to convince yourself that the result is indeed:
That is, the probability of measuring is 100% (in the absence of noise and errors) and the probability for measuring any other state is zero.
This two-qubit example was an especially clean case; Grover's algorithm will not always work out to yield a 100% chance of measuring the target state. Rather, it will amplify the probability of measuring the target state. Also, the Grover operator may need to be repeated more than once.
In the next section, we will put this algorithm into practice using real IBM® quantum computers.
Obvious caveat
In order to apply Grover's algorithm, we had to build the Grover operator, which means we must be able to flip the phase on states that satisfy our solution criteria. This begs the question: if we know our solution set so well that we can design a quantum circuit to label each one, what are we searching for?! The answer is three-fold, and we will revisit this throughout the tutorial:
(1) These kinds of query algorithms often involve two parties: one who has the oracle that establishes the solution criteria, and another who is trying to guess/find a solution state. The fact that one person can build the oracle does not negate the need for search.
(2) There are problems for which it is easier to specify a solution criterion than it is to find the solution. The best-known example of this is probably identifying prime factors of large numbers. Grover's algorithm is not particularly effective at solving that specific problem; we would use Shor's algorithm for prime factoring. This is just an example to point out that knowing the criterion on the behavior of a state is not always the same as knowing the state.
(3) Grover's algorithm does not only return classical data. True, if we make a measurement of the final state after repetitions of the Grover operator, we are likely to obtain classical information identifying the solution state. But what if we don't want classical information; what if we want a solution state prepared on a quantum computer for further use in another algorithm? Grover's algorithm actually produces a quantum state with the solutions heavily weighted. So you may expect to find Grover's algorithm as a subroutine in more complicated quantum algorithms.
With these in mind, let us work through several examples. We'll begin with an example in which the solution state is clearly specified so we can follow the logic of the algorithm, and we will move on to examples in which the usefulness of Grover's algorithm becomes more clear.
General imports and approach
We start by importing several necessary packages.
# Built-in modules
import math
# Imports from Qiskit
from qiskit import QuantumCircuit
from qiskit.circuit.library import grover_operator, MCMTGate, ZGate
from qiskit.visualization import plot_distribution
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
Throughout this and other tutorials, we will use a framework for quantum computing known as "Qiskit patterns", which breaks workflows into the following steps:
- Step 1: Map classical inputs to a quantum problem
- Step 2: Optimize problem for quantum execution
- Step 3: Execute using Qiskit Runtime Primitives
- Step 4: Post-processing and classical analysis
We will generally follow these steps, though we may not always explicitly label them.
Activity 1: Find a single given target state
Step 1: Map classical inputs to a quantum problem
We need the phase query gate to put an overall phase (-1) on solution states, and leave the non-solution states unaffected. Another way of saying this is that Grover's algorithm requires an oracle that specifies one or more marked computational basis states, where "marked" means a state with a phase of -1. This is done using a controlled-Z gate, or its multi-controlled generalization over qubits. To see how this works, consider a specific example of a bitstring {110}. We would like a circuit that acts on a state and applies a phase if (where we have flipped the order of the binary string, because of the notation in Qiskit, which puts the least significant (often 0) qubit on the right).
Thus, we want a circuit that accomplishes
We can use the multiple control multiple target gate (MCMTGate) to apply a Z gate controlled by all qubits (flip the phase if all qubits are in the state). Of course, some of the qubits in our desired state may be . Therefore, for those qubits we must first apply an X gate, then do the multiply-controlled Z gate, then apply another X gate to undo our change. The MCMTGate looks like this:
mcmt_ex = QuantumCircuit(3)
mcmt_ex.compose(MCMTGate(ZGate(), 3 - 1, 1), inplace=True)
mcmt_ex.draw(output="mpl", style="iqp")
Note that many qubits may be involved in the control process (here three qubits are), but no single qubit is denoted as a target. This is because the entire state gets an overall "-" sign (phase flip); the gate affects all the qubits equivalently. This is different from many other multiple qubit gates, like the CX gate, which has a single control qubit and a single target qubit.
In the following code, we define a phase query gate (or oracle) that does what we just described above: marks one or more input basis states defined through their bitstring representation. The MCMT gate is used to implement the multi-controlled Z-gate.
def grover_oracle(marked_states):
"""Build a Grover oracle for multiple marked states
Here we assume all input marked states have the same number of bits
Parameters:
marked_states (str or list): Marked states of oracle
Returns:
QuantumCircuit: Quantum circuit representing Grover oracle
"""
if not isinstance(marked_states, list):
marked_states = [marked_states]
# Compute the number of qubits in circuit
num_qubits = len(marked_states[0])
qc = QuantumCircuit(num_qubits)
# Mark each target state in the input list
for target in marked_states:
# Flip target bitstring to match Qiskit bit-ordering
rev_target = target[::-1]
# Find the indices of all the '0' elements in bitstring
zero_inds = [
ind for ind in range(num_qubits) if rev_target.startswith("0", ind)
]
# Add a multi-controlled Z-gate with pre- and post-applied X-gates (open-controls)
# where the target bitstring has a '0' entry
qc.x(zero_inds)
qc.compose(MCMTGate(ZGate(), num_qubits - 1, 1), inplace=True)
qc.x(zero_inds)
return qc
Now we choose a specific "marked" state to be our target, and apply the function we just defined. Let's see what kind of circuit it created.
marked_states = ["1110"]
oracle = grover_oracle(marked_states)
oracle.draw(output="mpl", style="iqp")
If qubits 1-3 are in the state, and qubit 0 is initially in the state, the first X gate will flip qubit 0 to and all qubits will be in This means the MCMT gate will apply an overall sign change or phase flip, as desired. For any other case, either qubits 1-3 are in the state, or qubit 0 is flipped to the state, and the phase flip will not be applied. We see that this circuit does indeed mark our desired state or the bitstring {1110}.
The full Grover operator consists of the phase query gate (oracle), Hadamard layers, and the operator. We can use the built-in grover_operator to construct this from the oracle we defined above.
grover_op = grover_operator(oracle)
grover_op.decompose(reps=0).draw(output="mpl", style="iqp")

As we argued above, we may need to apply the Grover operator multiple times. The optimal number of iterations, to maximize the amplitude of the target state in the absence of noise can be obtained from this expression:
Here is the number of solutions or target states. On modern noisy quantum computers, the experimentally optimal number of iterations might be different - but here we calculate and use this theoretical, optimal number using .
optimal_num_iterations = math.floor(
math.pi / (4 * math.asin(math.sqrt(len(marked_states) / 2**grover_op.num_qubits)))
)
print(optimal_num_iterations)
3
Let us now construct a circuit that includes the initial Hadamard gates to create a superposition of all possible states, and apply the Grover operator the optimal number of times.
qc = QuantumCircuit(grover_op.num_qubits)
# Create even superposition of all basis states
qc.h(range(grover_op.num_qubits))
# Apply Grover operator the optimal number of times
qc.compose(grover_op.power(optimal_num_iterations), inplace=True)
# Measure all qubits
qc.measure_all()
qc.draw(output="mpl", style="iqp")

We have constructed our Grover circuit!
Step 2: Optimize problem for quantum hardware execution
We have defined our abstract quantum circuit, but we need to rewrite it in terms of gates that are native to the quantum computer we actually want to use. We also need to specify which qubits on the quantum computer should be used. For these reasons and others, we now must transpile our circuit. First, let us specify the quantum computer we wish to use.
There is code below for saving your credentials upon first use. Be sure to delete this information from the notebook after saving it to your environment, so that your credentials are not accidentally shared when you share the notebook. See Set up your IBM Cloud account and Initialize the service in an untrusted environment for more guidance.
# To run on hardware, select the backend with the fewest number of jobs in the queue
from qiskit_ibm_runtime import QiskitRuntimeService
# Syntax for first saving your token. Delete these lines after saving your credentials.
# QiskitRuntimeService.save_account(channel='ibm_quantum_platform', instance = '<YOUR_IBM_INSTANCE_CRN>', token='<YOUR_API_KEY>', overwrite=True, set_as_default=True)
# service = QiskitRuntimeService(channel='ibm_quantum_platform')
# Load saved credentials
service = QiskitRuntimeService()
backend = service.least_busy(operational=True, simulator=False)
backend.name
qiskit_runtime_service._resolve_cloud_instances:WARNING:2025-08-08 14:14:19,931: Default instance not set. Searching all available instances.
'ibm_brisbane'
Now we use a preset pass manager to optimize our quantum circuit for the backend we selected.
target = backend.target
pm = generate_preset_pass_manager(target=target, optimization_level=3)
circuit_isa = pm.run(qc)
# The transpiled circuit will be very large. Only draw it if you are really curious.
# circuit_isa.draw(output="mpl", idle_wires=False, style="iqp")
It is worth noting at this time that the depth of the transpiled quantum circuit is substantial.
print("The total depth is ", circuit_isa.depth())
print(
"The depth of two-qubit gates is ",
circuit_isa.depth(lambda instruction: instruction.operation.num_qubits == 2),
)
The total depth is 439
The depth of two-qubit gates is 113
These are actually quite large numbers, even for this simple case. Since all quantum gates (and especially two-qubit gates) experience errors and are subject to noise, a series of over 100 two-qubit gates would result in nothing but noise if the qubits were not extremely high-performing. Let's see how these perform.
Execute using Qiskit primitives
We want to make many measurements and see which state is the most likely. Such an amplitude amplification is a sampling problem that is suitable for execution with the Sampler Qiskit Runtime primitive.
Note that the run() method of Qiskit Runtime SamplerV2 takes an iterable of primitive unified blocks (PUBs). For Sampler, each PUB is an iterable in the format (circuit, parameter_values). However, at a minimum, it takes a list of quantum circuit(s).
# To run on a real quantum computer (this was tested on a Heron r2 processor and used 4 sec. of QPU time)
from qiskit_ibm_runtime import SamplerV2 as Sampler
sampler = Sampler(mode=backend)
sampler.options.default_shots = 10_000
result = sampler.run([circuit_isa]).result()
dist = result[0].data.meas.get_counts()
To get the most out of this experience, we highly recommend you run your experiments on the real quantum computers available from IBM Quantum. However, if you have exhausted your QPU time, you can uncomment the lines below to complete this activity using a simulator.
# To run on local simulator:
# from qiskit.primitives import StatevectorSampler as Sampler
# sampler = Sampler()
# result = sampler.run([qc]).result()
# dist = result[0].data.meas.get_counts()
Step 4: Post-process and return result in desired classical format
Now we can plot the results of our sampling in a histogram.
plot_distribution(dist)

We see that Grover's algorithm returned the desired state with the highest probability by far, at least an order of magnitude higher than other options. In the next activity, we will use the algorithm in a way that is more consistent with the two-party workflow of a query algorithm.
Check your understanding
Read the questions below, think about your answer, then click the triangle to reveal the solution.
We just searched for a single solution in a set of possible states. We determined the optimal number of repetitions of the Grover operator to be . Would this optimal number have increased or decreased if we had searched for (a) any of several solutions, or (b) a single solution in a space of more possible states?
Answer:
Recall that as long as the number of solutions is small compared to the entire space of solutions, we can expand the sine function around small angles and use