Grover's algorithm
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.
# 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