Skip to main content
KetQat

Appearance

Lesson 750 min

Classical versus quantum complexity

BQP, query and circuit complexity, and how to read claims of quantum advantage.

After this lesson you can

  • Define P, BPP and BQP and state the known inclusions between them and PP and PSPACE
  • Distinguish query complexity from circuit complexity and explain why lower bounds are known for one and not the other
  • State the conditions under which the speed-ups of Shor, Grover, HHL and Hamiltonian simulation hold, including input and output assumptions
  • Explain what dequantization results show and what they do not
  • Apply a checklist to an advantage claim, separating theorems, conjectures and empirical observations
  • Compute a wall-clock crossover for Grover search under explicitly stated, illustrative timing assumptions

Read first: Introductory quantum algorithms, Grover's algorithm, Quantum phase estimation

Why complexity theory belongs in an algorithms course

Every quantum algorithm in this course comes with a claim about speed, and those claims differ enormously in strength. Some are theorems about a restricted model, some rest on the belief that a classical problem is hard, and some are numerical observations on small instances. This lesson gives you the vocabulary to tell them apart and a habit of asking what exactly is being compared.

Complexity classes in brief

A decision problem asks a yes/no question about an input of nn bits. Three classes matter here.

  • P: problems a deterministic classical algorithm solves in time polynomial in nn.
  • BPP: problems a randomised classical algorithm solves in polynomial time with error probability at most 1/31/3 on every input. Repeating and taking a majority vote drives the error down exponentially, so the constant 1/31/3 is arbitrary.
  • BQP: problems solved with error at most 1/31/3 by a uniform family of quantum circuits of polynomial size, measured at the end. "Uniform" means a classical computer can write down the circuit for size nn in polynomial time, which rules out hiding the answer in the circuit design.

The known relationships are

P⊆BPP⊆BQP⊆PP⊆PSPACE.\mathrm{P} \subseteq \mathrm{BPP} \subseteq \mathrm{BQP} \subseteq \mathrm{PP} \subseteq \mathrm{PSPACE}.

Bernstein and Vazirani defined BQP and showed BPP⊆BQP⊆PSPACE\mathrm{BPP} \subseteq \mathrm{BQP} \subseteq \mathrm{PSPACE} (Bernstein and Vazirani 1997); Adleman, DeMarrais and Huang tightened the upper bound to PP (Adleman, DeMarrais and Huang 1997). The inclusion BPP⊆BQP\mathrm{BPP}\subseteq\mathrm{BQP} holds because a quantum computer can simulate classical randomness. The PSPACE bound holds because the amplitude of an outcome is a sum over exponentially many computational paths, which a classical machine can add up with polynomial memory, one path at a time; the PP bound refines the same path-sum idea.

What is not known matters more. Nobody has proved BPP≠BQP\mathrm{BPP} \neq \mathrm{BQP}; doing so would also separate P from PSPACE, a famous open problem. So every claimed exponential quantum speed-up for a decision problem rests on a conjecture about classical hardness. Factoring is in BQP by Shor's algorithm (Shor 1997), but factoring is not known to be outside BPP, or even outside P; the best known classical algorithms are super-polynomial. NP-complete problems are widely believed not to be in BQP, and the BBBV bound from the Grover lesson is evidence for that belief, not a proof.

Query complexity versus circuit complexity

In the query model the input is hidden behind an oracle and we count oracle calls. In the circuit model we count all gates. The two answer different questions.

Query complexity is where quantum lower bounds are actually provable. BBBV shows that unstructured search needs Ω(N)\Omega(\sqrt N) queries (BBBV 1997), and oracle problems exist for which quantum algorithms need super-polynomially (for some problems, exponentially) fewer queries than any classical algorithm; Bernstein and Vazirani gave a super-polynomial separation of this kind in the same paper. These are theorems.

They do not automatically say anything about running time on a real problem, for two reasons.

  1. The oracle must be built. In an application, the oracle is a circuit that evaluates a function, and each query costs its gate count. A N\sqrt N-query algorithm whose oracle needs 10610^6 gates is a 106N10^6\sqrt N-gate algorithm.
  2. Real problems have structure. A query lower bound assumes the algorithm learns about the input only through the oracle. A SAT formula is not a black box: classical SAT solvers exploit its clauses and routinely beat brute force by enormous factors, and Grover search over assignments competes against them, not against exhaustive search.

Circuit lower bounds, by contrast, are almost entirely out of reach: we cannot even prove that NP problems need super-linear classical circuits. That is why "quantum advantage" for concrete problems is always stated relative to the best known classical algorithm.

The main speed-ups and their fine print

Algorithm Speed-up and status Conditions that must hold
Shor: factoring, discrete logarithms super-polynomial over the best known classical algorithms; classical hardness is a conjecture a fault-tolerant machine large enough for modular exponentiation
Grover, amplitude amplification quadratic in queries; optimal in the query model (theorem) an efficient oracle; a classical competitor that cannot exploit structure; error-correction overhead small enough
HHL for linear systems exponential in NN under strong conditions sparse, well-conditioned matrix; efficient preparation of ∣b⟩\ket b; output is a quantum state, so only expectation values are cheap
Simulating quantum dynamics polynomial quantum algorithms for local Hamiltonians; no efficient classical algorithm known in general a Hamiltonian with local or sparse structure; a question answered by measurements of the evolved state

A few remarks on the rows.

Shor. The speed-up is real in the sense that no classical polynomial-time algorithm is known after decades of effort, but it is not proven. The resources needed to run it at a cryptographically relevant size are the subject of the resource-estimation lesson.

Grover. The quadratic improvement is proven but fragile in practice: on an error-corrected computer each logical operation is far slower than a classical operation. Babbush and coauthors analysed this trade-off with concrete surface-code constructions and concluded that quadratic speed-ups are unlikely to give a runtime advantage on early fault-tolerant devices, while higher polynomial speed-ups look more promising (Babbush et al. 2021). The exercise reproduces the shape of that argument with deliberately simple assumptions.

HHL. The algorithm of Harrow, Hassidim and Lloyd prepares a state proportional to A−1∣b⟩A^{-1}\ket b in time polylogarithmic in the dimension NN and polynomial in the condition number κ\kappa and the inverse precision (Harrow, Hassidim and Lloyd 2009). It does not output the vector xx: reading all NN entries would cost order NN. Aaronson's commentary lists the caveats (input loading, condition number, sparsity, output access) that must all be satisfied before an exponential advantage survives (Aaronson 2015).

Simulation. Lloyd showed that a quantum computer can efficiently simulate the time evolution of local Hamiltonians (Lloyd 1996). No efficient classical algorithm is known for general quantum dynamics, which makes this the most widely expected application. "Known" is again doing work here: for specific Hamiltonians, classical methods (tensor networks, quantum Monte Carlo) can be very effective.

Dequantization

Some proposed exponential speed-ups, notably for recommendation systems and low-rank linear algebra, assumed that the quantum algorithm can sample from its input data cheaply. Tang showed that a classical algorithm with comparable sampling access to the same data can solve the recommendation problem in time polylogarithmic in the dimension, removing the exponential gap (Tang 2019). Chia and coauthors extended this to a general framework for low-rank matrix problems (Chia et al. 2020). The classical algorithms are polynomially slower, often by large polynomials, so a polynomial quantum advantage may remain. Dequantization does not show that quantum machine learning is useless; it shows that an exponential speed-up claim must compare against classical algorithms given the same input model.

How to read an advantage claim

Ask these questions in order.

  1. What is counted? Queries, gates, circuit depth, wall-clock time, energy? A query advantage is not a time advantage until the oracle is costed.
  2. Against which classical method? The best known algorithm for that problem, or a convenient one? Brute-force search is almost never the right baseline.
  3. What are the input and output models? Is the data loaded into amplitudes for free? Is the output a quantum state when the user needs numbers?
  4. What is proven? Separate theorems (query bounds, complexity inclusions), conjectures (classical hardness of factoring) and empirical observations (a heuristic worked on these instances).
  5. Which overheads are included? Error correction can multiply qubit counts by a thousand or more and slow each logical operation by orders of magnitude.
  6. At what size does it matter? An asymptotic advantage can start beyond any practical size.

Worked example: when would Grover win?

Consider unstructured search with one marked item and an oracle that is equally cheap to evaluate classically and quantumly in gates. Let one classical query take tct_c seconds and one Grover iteration (oracle plus diffusion, on error-corrected hardware) take tqt_q seconds. Classical random search needs on average (N+1)/2(N+1)/2 queries and Grover needs about π4N\tfrac\pi4\sqrt N iterations, so the times are Tc≈Ntc/2T_c \approx N t_c/2 and Tq≈π4N tqT_q \approx \tfrac\pi4\sqrt N\,t_q. Setting them equal gives the crossover

N∗=π24(tqtc)2,T∗=N∗tc2=π28 tq2tc.N^\ast = \frac{\pi^2}{4}\Big(\frac{t_q}{t_c}\Big)^2, \qquad T^\ast = \frac{N^\ast t_c}{2} = \frac{\pi^2}{8}\,\frac{t_q^2}{t_c}.

The timing values below are illustrative assumptions chosen to show how the answer scales; they are not measurements of any device. Take tc=1 nst_c = 1\,\mathrm{ns}.

assumed tqt_q crossover size N∗N^\ast run time at crossover T∗T^\ast
10 μs10\,\mu\mathrm{s} 2.47×1082.47\times10^{8} 0.12 s0.12\,\mathrm s
100 μs100\,\mu\mathrm{s} 2.47×10102.47\times10^{10} 12.3 s12.3\,\mathrm s
1 ms1\,\mathrm{ms} 2.47×10122.47\times10^{12} 1,234 s≈211{,}234\,\mathrm s \approx 21 min

Two features generalise. The break-even time grows with the square of the quantum step time, so slow logical operations hurt quadratically. And beyond the crossover the advantage grows slowly: at N=λ2N∗N = \lambda^2N^\ast the classical search takes λ2T∗\lambda^2T^\ast and Grover takes λT∗\lambda T^\ast. With tq=1 mst_q = 1\,\mathrm{ms}, a tenfold saving (λ=10\lambda = 10) means about 3.4 hours of quantum computing against 34 hours classically. Parallelism makes it worse: splitting the search over PP classical machines divides TcT_c by PP, while splitting it over PP quantum machines divides TqT_q only by P\sqrt P. In the exercise you show that this moves N∗N^\ast up by a factor PP while leaving the break-even time T∗T^\ast unchanged.

Query counts alone look very different. For N=220N = 2^{20}, the exercise gives an expected 805 oracle calls for Grover search (including a final check and the rare retry), against 524,288.5 for classical random search: a factor of about 650. Whether that becomes a saving in time depends entirely on tq/tct_q/t_c.

Exercise: query counts and a crossover

In query-count-crossover you compute expected classical and Grover query counts, wall-clock times under stated assumptions, and the closed-form crossover. The checks compare your classical expectation with a seeded Monte Carlo simulation, check that Grover's expected queries approach π4N\tfrac\pi4\sqrt N, compare your closed-form crossover with an independent bisection, and confirm the scaling with parallelism and with tqt_q.

Common mistakes

  • Equating a query speed-up with a time speed-up. The oracle's gate count and the speed of logical gates decide the outcome.
  • Using exhaustive search as the classical baseline when the problem has exploitable structure.
  • Reading "exponential speed-up" without its conditions. For HHL-type algorithms, check input loading, conditioning, sparsity and output access.
  • Treating dequantization as a proof that quantum methods are useless. It removes some exponential gaps; polynomial ones can remain.
  • Treating an assumption as a fact. Every timing number in a crossover estimate must be labelled with where it came from.

Summary

P⊆BPP⊆BQP⊆PP⊆PSPACE\mathrm{P}\subseteq\mathrm{BPP}\subseteq\mathrm{BQP}\subseteq\mathrm{PP}\subseteq\mathrm{PSPACE} is what we know; that BQP is strictly larger than BPP is a conjecture. Quantum lower bounds are provable in the query model, but turning a query advantage into a time advantage needs an efficient oracle and an honest classical baseline. Shor's speed-up rests on the presumed classical hardness of factoring; Grover's is proven but quadratic and sensitive to error-correction overhead; HHL's exponential speed-up needs a list of conditions on input and output; simulation of quantum dynamics is the most broadly expected advantage. A simple crossover model shows that with slow logical operations, Grover search pays off only for very large problems and long runs. The lessons that follow apply the same scrutiny to QAOA, quantum machine learning and fault-tolerant resource estimates.

Exercises

Run these on your own computer. Each comes with automated checks: python -m pytest test_exercise.py. Nothing you write is sent to KetQat.

Query counts and an illustrative Grover crossover

introductory · about 30 min · needs numpy, pytest

Turn query counts into wall-clock times under assumptions you state, and find where Grover search would start to beat classical search. Every timing input is an assumption, not a measured hardware figure; the exercise is about how the answer depends on them.

Functions to implement in starter.py

Function Contract
classical_expected_queries(N, M=1) expected queries of random-order search without repetition: (N+1)/(M+1)(N+1)/(M+1)
grover_iterations(N, M=1) nearest-integer rule round⁡(π/(4θ)−1/2)\operatorname{round}(\pi/(4\theta) - 1/2), sin⁡θ=M/N\sin\theta = \sqrt{M/N}
grover_success_probability(N, M, k) sin⁡2((2k+1)θ)\sin^2((2k+1)\theta)
grover_expected_queries(N, M=1) (k+1)/pk(k+1)/p_k: each attempt makes kk Grover queries plus one checking query, repeated until success
classical_time(N, t_classical, processors=1) Ntc/(2P)N t_c / (2P)
grover_time(N, t_quantum, processors=1) π4N/P tq\tfrac\pi4\sqrt{N/P}\,t_q
crossover_size(t_classical, t_quantum, processors=1) N∗=π24P(tq/tc)2N^\ast = \tfrac{\pi^2}{4} P (t_q/t_c)^2

What the checks verify

  • Your classical expectation agrees with a seeded Monte Carlo simulation of random-order search (40,000 trials, tolerance of five standard errors).
  • The nearest-integer rule achieves at least 1−1/N1 - 1/N for one marked item, and Grover's expected query count approaches π4N\tfrac\pi4\sqrt N for large NN.
  • Your closed-form crossover agrees with an independent bisection on the two time functions, and the two times are equal there.
  • N∗N^\ast grows linearly with the number of processors and quadratically with tqt_q.

Run the checks

python -m pytest test_exercise.py

Going further

Show that the break-even time T∗=classical_time(N∗)T^\ast = \text{classical\_time}(N^\ast) does not depend on the number of processors. Then add an oracle cost: suppose each Grover iteration needs gg logical gates of time tgt_g each. Rewrite tqt_q in terms of gg and tgt_g and see how N∗N^\ast scales with gg.

Terminal
python -m pip install numpy pytest

starter.py

Python
"""Starter: query counts and an illustrative wall-clock crossover for unstructured search.

Every timing input here is an ASSUMPTION you choose, not a measured hardware figure.
The point of the exercise is how the crossover depends on those assumptions.
"""

import math


def classical_expected_queries(N, M=1):
    """Expected number of queries of a classical search that tries items in a uniformly random
    order without repetition until it hits one of M marked items among N: (N + 1) / (M + 1)."""
    raise NotImplementedError


def grover_iterations(N, M=1):
    """Nearest-integer rule round(pi/(4 theta) - 1/2), sin(theta) = sqrt(M/N)."""
    raise NotImplementedError


def grover_success_probability(N, M, k):
    """sin^2((2k+1) theta) with sin(theta) = sqrt(M/N)."""
    raise NotImplementedError


def grover_expected_queries(N, M=1):
    """Expected oracle queries when each attempt runs k Grover iterations (k queries), then checks
    the measured item with one more query, and repeats until it succeeds: (k + 1) / p."""
    raise NotImplementedError


def classical_time(N, t_classical, processors=1):
    """Expected wall-clock time of the classical search split over `processors` machines:
    each searches N/processors items, expected N/(2 processors) queries of t_classical seconds."""
    raise NotImplementedError


def grover_time(N, t_quantum, processors=1):
    """Wall-clock time of Grover search split over `processors` quantum machines, each searching
    N/processors items with (pi/4) sqrt(N/processors) iterations of t_quantum seconds."""
    raise NotImplementedError


def crossover_size(t_classical, t_quantum, processors=1):
    """Smallest N (real-valued) at which grover_time(N) equals classical_time(N):
    N* = (pi^2 / 4) * processors * (t_quantum / t_classical)^2."""
    raise NotImplementedError

test_exercise.py

Python
import importlib.util
import os
from pathlib import Path

def _load_target():
    name = os.environ.get("KETQAT_COMMONS_TARGET", "starter")
    path = Path(__file__).with_name(f"{name}.py")
    spec = importlib.util.spec_from_file_location(f"{Path(__file__).parent.name}_{name}", path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

target = _load_target()

import math

import numpy as np
import pytest


def test_classical_expectation_matches_a_monte_carlo_search():
    rng = np.random.default_rng(12)
    N, M, trials = 40, 3, 40000
    marked = set(range(M))
    total = 0
    for _ in range(trials):
        order = rng.permutation(N)
        total += next(i for i, x in enumerate(order, start=1) if x in marked)
    mc = total / trials
    exact = target.classical_expected_queries(N, M)
    # Standard error of the Monte Carlo mean is below 0.05 here; allow 5 of them.
    assert abs(mc - exact) < 0.25
    assert np.isclose(target.classical_expected_queries(N, 1), (N + 1) / 2)


def test_grover_iterations_and_success():
    assert target.grover_iterations(4, 1) == 1
    assert np.isclose(target.grover_success_probability(4, 1, 1), 1.0)
    assert target.grover_expected_queries(4, 1) == pytest.approx(2.0)
    for n in range(2, 16):
        N = 2**n
        k = target.grover_iterations(N, 1)
        assert target.grover_success_probability(N, 1, k) >= 1 - 1 / N - 1e-12


def test_grover_queries_scale_as_pi_over_four_root_n():
    for N in (2**16, 2**24, 2**32):
        ratio = target.grover_expected_queries(N, 1) / (math.pi / 4 * math.sqrt(N))
        assert 1.0 <= ratio < 1.01
    # Quadratically fewer than classical, asymptotically.
    assert target.grover_expected_queries(2**32) < 1e-4 * target.classical_expected_queries(2**32)


def _bisection_crossover(t_c, t_q, P):
    f = lambda logn: target.grover_time(math.exp(logn), t_q, P) - target.classical_time(math.exp(logn), t_c, P)
    lo, hi = 0.0, 200.0
    assert f(lo) > 0 > f(hi)
    for _ in range(200):
        mid = (lo + hi) / 2
        if f(mid) > 0:
            lo = mid
        else:
            hi = mid
    return math.exp(lo)


@pytest.mark.parametrize("t_c,t_q,P", [(1e-9, 1e-5, 1), (1e-9, 1e-3, 1), (1e-8, 1e-4, 1000), (2e-9, 5e-6, 64)])
def test_closed_form_crossover_matches_bisection(t_c, t_q, P):
    closed = target.crossover_size(t_c, t_q, P)
    assert closed == pytest.approx(_bisection_crossover(t_c, t_q, P), rel=1e-9)
    assert target.grover_time(closed, t_q, P) == pytest.approx(target.classical_time(closed, t_c, P), rel=1e-9)


def test_parallelism_moves_the_crossover_linearly():
    one = target.crossover_size(1e-9, 1e-5, 1)
    assert target.crossover_size(1e-9, 1e-5, 1000) == pytest.approx(1000 * one)
    # Slower quantum steps move it quadratically.
    assert target.crossover_size(1e-9, 1e-4, 1) == pytest.approx(100 * one)

Check your understanding

7 questions. Pass with 70% of the points. Answers are checked on the server; retakes are allowed. Explanations appear once you pass or after three complete attempts.

  1. Which of these statements are currently proven? Select all that apply.

    1 pt

    Select all that apply.

  2. An algorithm uses O(N)O(\sqrt N) queries to an oracle that is itself a circuit of GG gates. What is its gate count, and what does BBBV say about it?

    1 pt
  3. Which conditions must hold for HHL to keep an exponential advantage over classical linear solvers? Select all that apply.

    1 pt

    Select all that apply.

  4. What did Tang's 2019 dequantization result show?

    1 pt
  5. Using crossover_size from your query-count-crossover solution with the illustrative assumptions tc=10−9t_c = 10^{-9} s and tq=10−4t_q = 10^{-4} s on one processor each, what is the crossover size N∗N^\ast? Enter it in units of 101010^{10}.

    1 pt

    Computed by running exercise “query-count-crossover” on your computer.

  6. Same assumptions (tc=1t_c = 1 ns, tq=100 μt_q = 100\,\mus). What is the break-even running time T∗T^\ast in seconds?

    1 pt

    Computed by running exercise “query-count-crossover” on your computer.

  7. A press release says: "Our quantum algorithm solves optimisation problems 1,000 times faster than classical computers." Which question should you ask first?

    1 pt

Sign in with GitHub to check answers and save progress. Reading stays free without an account.

References

  1. Ethan Bernstein, Umesh Vazirani (1997). Quantum complexity theory. SIAM Journal on Computing 26(5), 1411-1473. doi:10.1137/S0097539796300921
  2. Leonard M. Adleman, Jonathan DeMarrais, Ming-Deh A. Huang (1997). Quantum computability. SIAM Journal on Computing 26(5), 1524-1540. doi:10.1137/S0097539795293639
  3. Charles H. Bennett et al. (1997). Strengths and weaknesses of quantum computing. SIAM Journal on Computing 26(5), 1510-1523. doi:10.1137/S0097539796300933
  4. Peter W. Shor (1997). Polynomial-time algorithms for prime factorization and discrete logarithms on a quantum computer. SIAM Journal on Computing 26(5), 1484-1509. doi:10.1137/S0097539795293172
  5. Lov K. Grover (1996). A fast quantum mechanical algorithm for database search. Proceedings of the 28th Annual ACM Symposium on Theory of Computing (STOC '96), 212-219. doi:10.1145/237814.237866
  6. Aram W. Harrow, Avinatan Hassidim, Seth Lloyd (2009). Quantum algorithm for linear systems of equations. Physical Review Letters 103, 150502. doi:10.1103/PhysRevLett.103.150502
  7. Scott Aaronson (2015). Read the fine print. Nature Physics 11, 291-293. doi:10.1038/nphys3272
  8. Seth Lloyd (1996). Universal quantum simulators. Science 273, 1073-1078. doi:10.1126/science.273.5278.1073
  9. Ewin Tang (2019). A quantum-inspired classical algorithm for recommendation systems. Proceedings of the 51st Annual ACM SIGACT Symposium on Theory of Computing (STOC 2019). doi:10.1145/3313276.3316310
  10. Nai-Hui Chia et al. (2020). Sampling-based sublinear low-rank matrix arithmetic framework for dequantizing quantum machine learning. Proceedings of the 52nd Annual ACM SIGACT Symposium on Theory of Computing (STOC 2020). doi:10.1145/3357713.3384314
  11. Ryan Babbush et al. (2021). Focus beyond quadratic speedups for error-corrected quantum advantage. PRX Quantum 2, 010103. doi:10.1103/PRXQuantum.2.010103
  12. Michael A. Nielsen, Isaac L. Chuang (2010). Quantum Computation and Quantum Information (10th Anniversary Edition). Cambridge University Press. doi:10.1017/CBO9780511976667