Curriculum / Real-World Quantum Python / Grover's Algorithm Implementation

Lesson 10 of 20Code challengePro+150 XP

Grover's Algorithm Implementation

Implement Grover's search algorithm with a configurable oracle and analyze its quadratic speedup.

Grover's Algorithm Implementation

Grover's algorithm searches an unsorted database of N items in O(√N) quantum queries: a quadratic speedup over classical O(N) linear search. For N = 10⁶ items: 1,000 quantum queries vs 1,000,000 classical.

The Search Problem

Given a Boolean function f: {0,1,...,N-1} → {0,1} with exactly one "marked" item x where f(x)=1, find x*. Classical: check each item in turn, expected N/2 queries. Quantum: O(√N) queries.

The oracle is a black box that marks the target: . It applies a phase flip to the target without revealing directly.

The Three Components

1. Initialization: Apply H to all n qubits. This creates the uniform superposition . All states start with equal amplitude .

2. Oracle : Phase-flip the target state. The target amplitude goes from to . All other amplitudes remain . This alone does not help: the probabilities are still all .

3. Diffusion operator D: "Inversion about the mean." If the current state has amplitudes with mean :

  • New amplitude: aₓ → 2ā − aₓ

After the oracle, the mean is slightly below 1/√N (pulled down by the negative target). Inversion about the mean:

  • Target: 2ā − (−1/√N) > 1/√N ✓ (grows)
  • Others: 2ā − (1/√N) < 1/√N ✓ (shrink)

Each Grover iteration rotates the state vector by approximately 2θ in the 2D subspace spanned by the target and all others. After k ≈ π/4 × √N iterations, the target amplitude reaches near 1.

Iteration Count

The optimal number of iterations is: k = ⌊π/4 × √N⌋ (for a single marked item)

Under-iterate: target probability not yet maximal. Over-iterate: amplitude wraps around and decreases again. For N=8 (n=3 qubits): k ≈ 2.

Block parse error

Invalid JSON in block:visualization: Unexpected non-whitespace character after JSON at position 1138 (line 2 column 1)

This is the opening of the lesson. The full walkthrough, the interactive circuit, and the graded challenge continue inside myqubit.

How this lesson works

A hands-on coding challenge. You write Qiskit-compatible Python in the browser editor, run it instantly via WebAssembly, watch the circuit and Bloch sphere react, and pass automatic output checks. The AI tutor Qubitus gives Socratic hints if you get stuck.

Part of: Real-World Quantum Python

Write production-quality quantum Python, circuit optimization, hybrid algorithms, cloud backends, noise modeling, and software engineering patterns.

This lesson is part of Pro

Unlock Real-World Quantum Python and all 10 tracks with Pro: $12.99/month, $79/year, or $97 lifetime. Start with the free track first if you are new.