WRITING/DESIGN PATTERNS/DISPATCH 1

Design Patterns for Optimizing Quantum Circuits, Dispatch 1

Twenty-six small rewrites that contestants used in two public quantum-circuit contests. Each comes with a before and after circuit, its effect on every cost function, and a machine-checked proof.

S@SID~25 MIN READ26 LEAN PROOFS
2public contests the patterns come from: ecdsa.fail and Google's Kaggle challenge
2numbers every scoreboard counts: Toffoli gates and qubits
4families of patterns, grouped by what they make cheaper
26patterns, each with an animated circuit, Qiskit code and a Lean proof
FIG. 0 / THIS DISPATCH AT A GLANCE. THREE RULES, THEN FOUR FAMILIES. HOVER A SQUARE.
ONE PATTERN, SAVES TOFFOLISONE PATTERN, PAYS TOFFOLIS TO SAVE QUBITSREAD TOP TO BOTTOM, OR JUMP TO ANY CARD
01 / THE SHORT VERSION

Most of a circuit's cost is cleanup, and cleanup can be made nearly free.

Two public contests opened in 2026 that ask the same question: here is a quantum subroutine, make it cheaper. ecdsa.fail asks for one elliptic-curve point addition, the inner loop of Shor's algorithm against Bitcoin and Ethereum signatures. Google Quantum AI's Kaggle contest asks for three subroutines from physics simulation, optimization and chemistry.

Thousands of teams, many of them working with AI coding agents, pushed those circuits down by large factors. When you read what they actually did, the same few dozen moves come up again and again. This dispatch collects twenty-six of them as design patterns: a small block of circuit, a cheaper block that does the same job, and the conditions under which the swap is safe.

Each pattern below has an animated before and after, the same block written in Qiskit, a plain statement of what it does to every cost function the contests use, and a proof checked by the Lean theorem prover. Three short sections first explain what is being counted and why.

02 / THE SCOREBOARD

Two numbers decide everything: Toffolis and qubits.

Neither contest scores speed on a real device. Both score two counts taken from the circuit itself: how many Toffoli gates it runs and how many qubits it needs at its widest point. Toffolis stand for running time, qubits stand for the size of the machine, and their product is roughly machine size times running time.

A product has one practical virtue: it sets an exchange rate. Almost any circuit can trade a scratch qubit for fewer Toffolis or the reverse, and a product only rewards trades that are a real net gain. Google's own two reference designs for point addition show it: one is narrow and slow, one is wide and fast, and their scores are within 7% of each other.

FIG. 1 / FOUR SCOREBOARDS, ONE IDEA. PICK ONE.
SCORE, LOWER IS BETTER
1% FEWER QUBITS IS WORTH
off the score
1% FEWER TOFFOLIS IS WORTH
off the score
3.2 × 10⁹
2.7M TOFFOLIS × 1,175 QUBITS
3.0 × 10⁹
2.1M TOFFOLIS × 1,425 QUBITS
Google's two reference points for secp256k1 point addition, drawn to scale: width is qubits, height is Toffolis, area is the score. Different shapes, nearly the same area.

Two details of these formulas shape the patterns. First, both contests count the Toffolis actually executed, averaged over runs. A gate that is applied only when a measurement came out 1 costs half. Second, the weighting is a choice: in the DQI task qubits are squared, so, in the paper's words, "a 1% reduction in qubits improves the score as much as a 2% reduction in Toffoli gates". A trade that pays on one scoreboard can lose on another.

03 / WHY ONE GATE IS EXPENSIVE

Error correction can do most gates directly. Not this one.

These circuits are meant for an error-corrected machine, where each logical qubit is spread over many physical ones and constantly checked. On such a machine the gates split into two classes. Clifford gates (X, CNOT, CZ, measurement) turn simple errors into simple errors, so the code can keep tracking them, and they are cheap. The gates that complete the set, T and Toffoli, do not have that property, and a theorem says no code can do every gate the safe way.

So a Toffoli is done indirectly. A helper qubit is prepared in a special "magic" state, many noisy copies are distilled into a few clean ones, and the gate is transferred onto the data using only Clifford gates and a measurement. The ecdsa.fail README states the consequence in one line:

Faster point addition ⇒ fewer Toffoli gates ⇒ fewer magic states ⇒ less physical hardware and less wall-clock time on a fault-tolerant quantum computer.

That is why the scoreboards charge for Toffolis and for nothing else. It is also the opening every pattern in the next section walks through: if a Toffoli can be replaced by a measurement and a Clifford gate, the scoreboard sees it as free.

FIG. 2 / THE PRICE LIST. HOVER OR TAP A GATE.
04 / HOW A LAPTOP REFEREES

No Hadamards, so an ordinary program can check every step.

A general quantum circuit cannot, in practice, be checked on a classical computer once it is more than a few dozen qubits wide. These can, because of what they leave out. The contest circuits contain reversible logic, sign and phase gates, and a "measure in the X basis and reset" step, but no Hadamard. Without it a circuit never branches: give it a definite input and every gate maps one bit string to one bit string, possibly with a sign attached.

So the referee runs the circuit like an ordinary program, keeping one bit per qubit and one running sign. If the bits and the sign are right on every input, the circuit is right on every superposition of inputs, because quantum mechanics is linear. A saving that comes from skipping cleanup or leaving a stray sign fails this check instead of scoring.

Try it on the simplest pattern in this dispatch. A scratch qubit t receives a AND b, is measured, and a repair gate fires when the outcome is 1. Flip the inputs and the outcome: the sign always comes back to plus.

FIG. 3 / THE REFEREE'S VIEW OF ONE ERASE. FLIP THE BITS.

The Lean proofs in this dispatch use exactly this model: a state is a list of bits, a sign, and a record of measurement outcomes. A pattern is proved by showing that the rewritten block and the original agree on bits and sign for every input and every outcome.

05 / PART 1 · ERASE BY MEASUREMENT

Forgetting does not need the expensive gate.

Quantum circuits are full of scratch values: a carry, a flag, a table entry, a product. Each one has to be returned to zero before its qubit can be reused, and the textbook way is to run the computation backwards, paying for it a second time.

The seven patterns in this part all rest on one observation. Measuring a scratch qubit in the X basis reveals nothing about its value, so the data survives. It only leaves a possible minus sign, and that sign can be cancelled by a gate the scoreboard does not charge for.

The code under each figure is Qiskit. Two idioms recur. "Measure in the X basis and reset" is written qc.h(q); qc.measure(q, c); qc.reset(q), and a gate that fires only when a measurement came out 1 sits inside with qc.if_test((c, 1)):. Each snippet is the smallest instance that shows the idea, so its size can differ from the figure above it. Every before and after pair was simulated against each other on random inputs.

P01 / ERASE BY MEASUREMENT

Erase a temporary AND by measurement

A scratch qubit t holds a AND b. The textbook cleanup applies the same Toffoli again, so every temporary AND costs two Toffolis.

Measure t in the X basis and reset it. If the outcome m is 1, the branches where t was 1 picked up a minus sign; a CZ on a and b puts a second minus sign on exactly those branches, and the two cancel.

Before: Uncompute with a second Toffoli, 2. After: Measure and fix, 1 (toffolis per temporary and).

  • Toffolis: Lower. 2 → 1 per temporary AND.
  • Qubits: Same. Same scratch qubit; adds one classical bit.
  • Toffoli × qubit scores: Lower. Falls by the share of Toffolis that were cleanup; close to half in adder-heavy circuits.
  • Q² × Toffoli (DQI): Lower. Same Toffoli gain; width is untouched.
from qiskit import QuantumCircuit

def before():
    a, b, t = 0, 1, 2
    qc = QuantumCircuit(3)
    qc.ccx(a, b, t)  # t = a AND b
    # ... use t ...
    qc.ccx(a, b, t)  # uncompute with a second Toffoli
    return qc
def after():
    a, b, t = 0, 1, 2
    qc = QuantumCircuit(3, 1)
    qc.ccx(a, b, t)  # t = a AND b
    # ... use t ...
    # measure in X, reset
    qc.h(t); qc.measure(t, 0); qc.reset(t)
    with qc.if_test((qc.clbits[0], 1)):
        qc.cz(a, b)  # repair the sign
    return qc
NEEDS
a and b unchanged since the compute; mid-circuit measurement and classical control
SEEN IN
Throughout the public circuits of both contests (Gidney 2018)
PROOF
QCP.P01.correct, all inputs and both outcomes
P04 / ERASE BY MEASUREMENT

Ripple-carry adder with measured carries

An n-bit adder computes n−1 carries, each a majority of three bits, and must remove them again. Doing both with Toffolis costs 2(n−1).

Each carry is one temporary AND, so P01 applies to every one of them. The reverse sweep is still there, but it is made of CNOTs, measurements and conditional CZs. The animation shows one bit position.

Before: Carries removed with Toffolis, 2(n−1). After: Carries measured away, n−1 (toffolis, n-bit adder).

  • Toffolis: Lower. 2(n−1) → n−1: every adder halves.
  • Qubits: Same. n−1 carry qubits either way.
  • Toffoli × qubit scores: Lower. Up to 2× on adder-heavy circuits such as point addition.
  • Q² × Toffoli (DQI): Depends. Lower if the carries fit under the peak width; otherwise see P12.
from qiskit import QuantumCircuit

def before():  # one bit position of the adder
    # c = carry in, c2 = carry out
    a, b, c, c2 = 0, 1, 2, 3
    qc = QuantumCircuit(4)
    qc.cx(c, a); qc.cx(c, b)
    # c2 = majority(a, b, c)
    qc.ccx(a, b, c2); qc.cx(c, c2)
    # ... higher bits use c2 ...
    # remove the carry: a Toffoli
    qc.cx(c, c2); qc.ccx(a, b, c2)
    qc.cx(c, a); qc.cx(a, b)  # b = a + b + c
    return qc
def after():
    a, b, c, c2 = 0, 1, 2, 3
    qc = QuantumCircuit(4, 1)
    qc.cx(c, a); qc.cx(c, b)
    qc.ccx(a, b, c2); qc.cx(c, c2)
    # ... higher bits use c2 ...
    qc.cx(c, c2)
    # measure the carry away
    qc.h(c2); qc.measure(c2, 0); qc.reset(c2)
    with qc.if_test((qc.clbits[0], 1)):
        qc.cz(a, b)
    qc.cx(c, a); qc.cx(a, b)
    return qc
NEEDS
n−1 clean carry qubits for the duration of the addition
SEEN IN
Adders throughout both contests (Gidney 2018)
PROOF
QCP.P04.correct8, 8 bits, every input and record
P05 / ERASE BY MEASUREMENT

Erase a bilinear product by measurement

A register holds c = a·b, where the product is bilinear over GF(2): a carry-less product or a finite-field product. Uncomputing it means running the multiplier a second time.

Measure every bit of c in the X basis. The leftover sign is a sum of terms aᵢ·bⱼ with classically known coefficients, which is exactly what a set of CZ gates cancels. The multiplier runs once.

Before: Uncompute with the multiplier, 2r. After: Measure, then CZ pairs, r (toffolis, r = multiplier rank).

  • Toffolis: Lower. Uncompute costs 0 instead of the multiplier rank r (42 for GF(4096)).
  • Qubits: Same. No extra qubits.
  • Toffoli × qubit scores: Lower. Halves every multiply-then-erase.
  • Q² × Toffoli (DQI): Lower. Used throughout the public DQI decoders.
from qiskit import QuantumCircuit
# c = a * b, carry-less, 2 x 2 bits
A, B, C = [0, 1], [2, 3], [4, 5, 6]

def multiply(qc):
    for i in range(2):
        for j in range(2):
            qc.ccx(A[i], B[j], C[i + j])

def before():
    qc = QuantumCircuit(7)
    multiply(qc)
    # ... use c ...
    multiply(qc)  # uncompute: the multiplier again
    return qc
def after():
    qc = QuantumCircuit(7, 3)
    multiply(qc)
    # ... use c ...
    for k in range(3):
        qc.h(C[k]); qc.measure(C[k], k); qc.reset(C[k])
        with qc.if_test((qc.clbits[k], 1)):
            # CZ for every term a_i b_j of c_k
            for i in range(2):
                if 0 <= k - i < 2:
                    qc.cz(A[i], B[k - i])
    return qc
NEEDS
Both factors still present and unchanged at repair time (or defer the repair, P06)
SEEN IN
Kaggle DQI decoders erase GF(4096) words this way throughout
PROOF
QCP.P05.correct4, 4×4 product, all inputs and 2⁷ records
P07 / ERASE BY MEASUREMENT

Multi-controlled X through an AND ladder

A flag that depends on n controls (an equality test, a zero test, a lookup address match) is built as a ladder of ANDs and then taken down again: 2n−3 Toffolis.

Take the ladder down from the top with P01. Each rung is erased while the two qubits it was made from are still alive, so every repair is a CZ.

Before: Ladder down with Toffolis, 5. After: Ladder measured away, 3 (toffolis, 4 controls (2n−3 → n−1)).

  • Toffolis: Lower. 2n−3 → n−1 (5 → 3 in the animation).
  • Qubits: Same. Same n−2 ladder qubits.
  • Toffoli × qubit scores: Lower. Applies to every test and address decode.
  • Q² × Toffoli (DQI): Lower. If the ladder is kept across its use: 11 instead of 24 for a 12-bit zero test.
from qiskit import QuantumCircuit

def before():  # target ^= c0 c1 c2 c3
    c0, c1, c2, c3, tgt, u1, u2 = range(7)
    qc = QuantumCircuit(7)
    qc.ccx(c0, c1, u1)
    qc.ccx(u1, c2, u2)
    qc.ccx(u2, c3, tgt)
    qc.ccx(u1, c2, u2)  # ladder down: two more Toffolis
    qc.ccx(c0, c1, u1)
    return qc
def after():
    c0, c1, c2, c3, tgt, u1, u2 = range(7)
    qc = QuantumCircuit(7, 2)
    qc.ccx(c0, c1, u1)
    qc.ccx(u1, c2, u2)
    qc.ccx(u2, c3, tgt)
    qc.h(u2); qc.measure(u2, 0); qc.reset(u2)
    with qc.if_test((qc.clbits[0], 1)):
        qc.cz(u1, c2)  # u1 is still alive
    qc.h(u1); qc.measure(u1, 1); qc.reset(u1)
    with qc.if_test((qc.clbits[1], 1)):
        qc.cz(c0, c1)
    return qc
NEEDS
n−2 clean ladder qubits; erase in reverse order of computation
SEEN IN
Kaggle DQI scan: an 11-AND zero test at each of 4,025 positions
PROOF
QCP.P07.correct6, 6 controls
P10 / ERASE BY MEASUREMENT

Measure-first peephole

A Toffoli writes into a qubit that is X-measured and reset before anything else reads it.

Swap the order. Measuring first and applying a conditional CZ afterwards gives the same state, with no condition on what the target held. P01 is the special case where the target held a·b.

Before: Toffoli, then measure, 1. After: Measure, then conditional CZ, 0 (toffolis per site).

  • Toffolis: Lower. 1 → 0 at each site.
  • Qubits: Same. Unchanged.
  • Toffoli × qubit scores: Lower. Small: only where generators left such a pair.
  • Q² × Toffoli (DQI): Lower. Same.
from qiskit import QuantumCircuit

def before():
    a, b, t = 0, 1, 2
    qc = QuantumCircuit(3, 1)
    qc.ccx(a, b, t)
    qc.h(t); qc.measure(t, 0); qc.reset(t)
    return qc
def after():
    a, b, t = 0, 1, 2
    qc = QuantumCircuit(3, 1)
    # measure first
    qc.h(t); qc.measure(t, 0); qc.reset(t)
    with qc.if_test((qc.clbits[0], 1)):
        qc.cz(a, b)  # the Toffoli became a CZ
    return qc
NEEDS
Nothing reads the target between the Toffoli and the measurement
SEEN IN
Clean-up passes on Kaggle circuits
PROOF
QCP.P10.ccx_then_measure, any wires
P16 / ERASE BY MEASUREMENT

A controlled swap before two measurements is free

Two wires are conditionally swapped and then both measured in the X basis. The swap costs one Toffoli per pair of wires.

Write a XOR b onto the second wire with a CNOT, measure the first wire, apply a conditional CZ between the control and the second wire, then measure it. The original outcomes are recovered as r = u XOR v and s = v.

Before: Swap, then measure both, 1. After: CNOT, measure, CZ, measure, 0 (toffolis per swapped pair).

  • Toffolis: Lower. 1 → 0 per swapped pair.
  • Qubits: Same. Unchanged.
  • Toffoli × qubit scores: Lower. Applies wherever a swap feeds a readout.
  • Q² × Toffoli (DQI): Lower. 48 Toffolis per run in the DQI frontier, as reported in those write-ups.
from qiskit import QuantumCircuit

def before():
    c, a, b = 0, 1, 2
    qc = QuantumCircuit(3, 2)
    qc.cswap(c, a, b)
    qc.h(a); qc.measure(a, 0); qc.reset(a)  # outcome r
    qc.h(b); qc.measure(b, 1); qc.reset(b)  # outcome s
    return qc
def after():
    c, a, b = 0, 1, 2
    qc = QuantumCircuit(3, 2)
    qc.cx(a, b)  # b holds a XOR b
    qc.h(a); qc.measure(a, 0); qc.reset(a)  # outcome u
    with qc.if_test((qc.clbits[0], 1)):
        qc.cz(c, b)
    qc.h(b); qc.measure(b, 1); qc.reset(b)  # outcome v
    # downstream: use r = u XOR v and s = v
    return qc
NEEDS
Both wires measured with nothing in between; later repairs read the relabelled bits
SEEN IN
Kaggle DQI frontier: 48 controlled swaps removed (public write-ups)
PROOF
QCP.P16.correct and .record
P25 / ERASE BY MEASUREMENT

Measurement-based unlookup

A register holds the table entry T[address] for an L-entry table. Clearing it by running the lookup again costs as much as the lookup, L−2 Toffolis.

Measure the register. The leftover sign is one classical bit per address. Split the address in two halves, make a one-hot code of each, and apply CZ between them wherever that bit is 1. Only the two one-hot codes cost Toffolis.

Before: Unload by a second lookup, 28. After: Measure, then phase fix, 16 (toffolis, 16-entry table, load + unload).

  • Toffolis: Lower. L−2 → about 2√L, whatever the word width (14 → 2 for 16 entries).
  • Qubits: Same. Scratch for the one-hot code reuses the freed register when it is wide enough.
  • Toffoli × qubit scores: Lower. Nearly halves every load-use-unload.
  • Q² × Toffoli (DQI): Lower. Same, if the one-hot code fits under the peak.
from qiskit import QuantumCircuit
TABLE = [2, 1, 3, 0]  # 4 entries, 2-bit words

def lookup(qc):  # out ^= TABLE[address]
    for i, word in enumerate(TABLE):
        flip = [q for q in (0, 1) if not (i >> q) & 1]
        if flip: qc.x(flip)
        for j in (0, 1):
            if (word >> j) & 1:
                qc.ccx(0, 1, 2 + j)
        if flip: qc.x(flip)

def before():
    qc = QuantumCircuit(4)
    lookup(qc)
    # ... use out ...
    lookup(qc)  # unload: the lookup again
    return qc
def after():
    qc = QuantumCircuit(4, 2)
    lookup(qc)
    # ... use out ...
    for j in (0, 1):
        qc.h(2 + j); qc.measure(2 + j, j); qc.reset(2 + j)
        # bit j of every entry
        f = [(w >> j) & 1 for w in TABLE]
        # sign (-1)^f[address]
        with qc.if_test((qc.clbits[j], 1)):
            if f[0] ^ f[1]: qc.z(0)
            if f[0] ^ f[2]: qc.z(1)
            if f[0] ^ f[1] ^ f[2] ^ f[3]: qc.cz(0, 1)
    return qc
NEEDS
Address unchanged; about √L scratch qubits, usually the ones just freed
SEEN IN
Lookups in the Kaggle 1/√x and DQI circuits (Berry et al. 2019)
PROOF
QCP.P25.correct, 16 entries, 2¹⁸ records
06 / PART 2 · MERGE AND CANCEL

Some savings need no understanding of the circuit at all.

The next five are identities on gates that are already there. They do not need to know what the circuit computes, so they can run as an automatic pass over a finished gate list. Each site saves one or two Toffolis; a circuit with half a billion gates has a lot of sites.

We ran the first two as a post-pass on other teams' ecdsa.fail circuits. The cancellation rule alone took 1.35% off the official score of a 651-qubit entry. That is also roughly where local rewriting ends: larger gains need the kind of knowledge in Part 3.

P02 / MERGE AND CANCEL

Cancel a Toffoli pair across commuting gates

The same Toffoli appears twice with other gates in between. Generators produce this wherever one block's cleanup is followed by a neighbouring block's setup.

A Toffoli is its own inverse. If every gate between the two copies commutes with it, slide one copy next to the other and both disappear. A Toffoli commutes with any gate that does not write its controls or read its target.

Before: Toffoli, commuting gates, same Toffoli, 2. After: Only the gates in between remain, 0 (toffolis per pair).

  • Toffolis: Lower. −2 per pair found.
  • Qubits: Same. Unchanged.
  • Toffoli × qubit scores: Lower. Measured on ecdsa.fail: −1.1% (652 qubits) and −1.35% (651 qubits) of the official score.
  • Q² × Toffoli (DQI): Lower. Proportional to the pairs found; frontier circuits have few left.
from qiskit import QuantumCircuit

def before():
    a, b, t, u = 0, 1, 2, 3
    qc = QuantumCircuit(4)
    qc.ccx(a, b, t)
    qc.cx(a, u)  # these commute with the Toffoli:
    qc.cz(b, u)  # they never write a, b or read t
    qc.ccx(a, b, t)
    return qc
def after():
    a, b, t, u = 0, 1, 2, 3
    qc = QuantumCircuit(4)
    qc.cx(a, u)
    qc.cz(b, u)
    return qc
NEEDS
Both copies under the same classical condition; everything in between commutes
SEEN IN
Our ecdsa.fail post-pass: 6.1M and 8.4M Toffolis removed from a 652- and a 651-qubit circuit
PROOF
QCP.P02.cancel_across and three commutation lemmas, any wires
P03 / MERGE AND CANCEL

Merge two Toffolis that share two wires

Two Toffolis write a·b and a·c into the same target.

a·b XOR a·c equals a·(b XOR c). Form b XOR c in place with a CNOT, apply one Toffoli, and undo the CNOT. The same works for two Toffolis with the same controls and different targets.

Before: a·b and a·c into one target, 2. After: a·(b XOR c), 1 (toffolis).

  • Toffolis: Lower. 2 → 1 per merge.
  • Qubits: Same. Unchanged.
  • Toffoli × qubit scores: Lower. Measured on ecdsa.fail: a further −0.14%.
  • Q² × Toffoli (DQI): Lower. Proportional to merges found.
from qiskit import QuantumCircuit

def before():
    a, b, c, t = 0, 1, 2, 3
    qc = QuantumCircuit(4)
    qc.ccx(a, b, t)  # t ^= a b
    qc.ccx(a, c, t)  # t ^= a c
    return qc
def after():
    a, b, c, t = 0, 1, 2, 3
    qc = QuantumCircuit(4)
    qc.cx(c, b)  # b holds b XOR c
    qc.ccx(a, b, t)  # t ^= a (b XOR c)
    qc.cx(c, b)
    return qc
NEEDS
No ancilla. Gates between the two must commute with both
SEEN IN
Our ecdsa.fail post-pass: 832,694 merges on the 651-qubit circuit
PROOF
QCP.P03.merge_shared_control_target, any wires
P13 / MERGE AND CANCEL

One Toffoli for a product of sums

Four Toffolis add a·c, a·d, b·c and b·d into one target.

The four terms are (a XOR b)·(c XOR d). Two CNOTs form the sums in place, one Toffoli multiplies them, two CNOTs restore the inputs. The same conjugation delivers one product to several targets at once.

Before: One Toffoli per term, 4. After: (a XOR b)·(c XOR d), 1 (toffolis).

  • Toffolis: Lower. 4 → 1 (and 3 → 1 for one product sent to three targets).
  • Qubits: Same. No ancilla.
  • Toffoli × qubit scores: Lower. The basis of the chemistry loaders' Toffoli counts.
  • Q² × Toffoli (DQI): Lower. Used inside field multipliers (P20).
from qiskit import QuantumCircuit

def before():
    a, b, c, d, t = range(5)
    qc = QuantumCircuit(5)
    qc.ccx(a, c, t)
    qc.ccx(a, d, t)
    qc.ccx(b, c, t)
    qc.ccx(b, d, t)
    return qc
def after():
    a, b, c, d, t = range(5)
    qc = QuantumCircuit(5)
    # a holds a XOR b, c holds c XOR d
    qc.cx(b, a); qc.cx(d, c)
    qc.ccx(a, c, t)  # t ^= (a XOR b)(c XOR d)
    qc.cx(d, c); qc.cx(b, a)
    return qc
NEEDS
All four inputs alive together; target not read in between
SEEN IN
Kaggle chemistry loaders: lookup compilers count products of sums, not monomials
PROOF
QCP.P13.paired_product and .fanout3, any wires
P15 / MERGE AND CANCEL

Phase fold through a dirty target

A Toffoli writes a·b into t, a CZ between c and t reads it, and the same Toffoli removes it again.

The CZ sees t XOR a·b, so its effect is a CZ on c and t plus a sign on a·b·c. That sign is a single CCZ. The qubit t can hold anything.

Before: Toffoli, CZ, Toffoli, 2. After: CCZ and CZ, 1 (toffolis).

  • Toffolis: Lower. 2 → 1 per fold.
  • Qubits: Same. Unchanged.
  • Toffoli × qubit scores: Lower. Tiny in practice: few sites exist.
  • Q² × Toffoli (DQI): Lower. Seven Toffolis out of about 395,000.
from qiskit import QuantumCircuit

def before():
    a, b, c, t = 0, 1, 2, 3
    qc = QuantumCircuit(4)
    qc.ccx(a, b, t)
    qc.cz(c, t)
    qc.ccx(a, b, t)
    return qc
def after():
    a, b, c, t = 0, 1, 2, 3
    qc = QuantumCircuit(4)
    qc.ccz(a, b, c)
    qc.cz(c, t)
    return qc
NEEDS
Nothing else touches t or c between the three gates
SEEN IN
Kaggle DQI frontier: seven folds in a 395,000-Toffoli circuit (public write-up)
PROOF
QCP.P15.phase_fold, any wires
P24 / MERGE AND CANCEL

A quadratic form costs its rank, not its number of terms

Three Toffolis add a·b, b·c and c·a into a target: the majority of three bits, which is every adder carry.

The sum equals (a XOR c)·(b XOR c) XOR c. In general, k products added into one target can be rewritten as r products of sums, where r is the rank of the quadratic form (Dickson). P03 and P13 are rank-one cases.

Before: One Toffoli per term, 3. After: (a XOR c)·(b XOR c) XOR c, 1 (toffolis).

  • Toffolis: Lower. 3 → 1 here; k terms → rank in general.
  • Qubits: Same. No ancilla.
  • Toffoli × qubit scores: Lower. Already built into good generators, so little is left for a post-pass.
  • Q² × Toffoli (DQI): Lower. Same.
from qiskit import QuantumCircuit

def before():  # t ^= majority(a, b, c)
    a, b, c, t = 0, 1, 2, 3
    qc = QuantumCircuit(4)
    qc.ccx(a, b, t)
    qc.ccx(b, c, t)
    qc.ccx(a, c, t)
    return qc
def after():
    a, b, c, t = 0, 1, 2, 3
    qc = QuantumCircuit(4)
    qc.cx(c, a); qc.cx(c, b)
    qc.ccx(a, b, t)  # (a XOR c)(b XOR c)
    qc.cx(c, t)  # ... XOR c
    qc.cx(c, b); qc.cx(c, a)
    return qc
NEEDS
All operands alive at the same time
SEEN IN
Adder carries everywhere; rank sweeps on Kaggle circuits found nothing left over
PROOF
QCP.P24.majority, any wires. The general theorem is not formalised
07 / PART 3 · CHEAPER BUILDING BLOCKS

The biggest savings come from knowing what the block is for.

A general-purpose optimizer sees gates. A circuit generator knows it is building a lookup, a shift, or a multiplication in a finite field, and can pick a better construction for exactly that job. These ten patterns are such constructions.

Several of them depend on a fact about the data: a wire that is known to be zero, a factor that is a known constant, an address that has not changed. That is why they live in generators and not in compilers.

P08 / CHEAPER BUILDING BLOCKS

Linear maps cost no Toffolis

Multiplying a field element by a known constant with a general multiplier means loading the constant into a scratch word and paying the full multiplier.

Multiplication by a constant is a linear map over GF(2), and so are squaring, basis changes and cyclic shifts. Any invertible linear map is a network of CNOTs and swaps, applied in place. The animation multiplies by x in GF(16).

Before: General multiplier with a loaded constant, r. After: Three swaps and one CNOT, in place, 0 (toffolis, multiply by a known constant).

  • Toffolis: Lower. Multiplier rank r → 0.
  • Qubits: Lower. No scratch word for the constant.
  • Toffoli × qubit scores: Lower. Both factors fall.
  • Q² × Toffoli (DQI): Lower. Doubly useful: the saved word counts twice.
from qiskit import QuantumCircuit
# GF(4): w^2 = w + 1; out ^= w * x
X, OUT, K = [0, 1], [2, 3], [4, 5]

def before():
    qc = QuantumCircuit(6)
    qc.x(K[1])  # load the constant w = (0, 1)
    qc.ccx(X[0], K[0], OUT[0]); qc.ccx(X[1], K[1], OUT[0])
    qc.ccx(X[0], K[1], OUT[1]); qc.ccx(X[1], K[0], OUT[1])
    # general multiplier: 5 Toffolis
    qc.ccx(X[1], K[1], OUT[1])
    qc.x(K[1])  # unload
    return qc
def after():
    qc = QuantumCircuit(6)
    # w * (x0 + x1 w) = x1 + (x0 + x1) w
    qc.cx(X[1], OUT[0])
    qc.cx(X[0], OUT[1]); qc.cx(X[1], OUT[1])
    # in place it is just: qc.swap(X[0], X[1]); qc.cx(X[0], X[1])
    return qc
NEEDS
One factor classical. Worth restructuring an algorithm so that it is
SEEN IN
Kaggle DQI decoders: evaluation steps and constant multiplications
PROOF
QCP.P08.correct (one instance; the general fact is linear algebra)
P09 / CHEAPER BUILDING BLOCKS

Controlled swap from one Toffoli

A controlled swap is its own gate in both contests' gate sets and is counted as one Toffoli.

It equals a CNOT, a Toffoli and a CNOT. The count does not change, but once swaps are written this way the merge and cancel rules of Part 2 apply to them, and so does P17.

Before: Controlled swap, 1. After: CNOT, Toffoli, CNOT, 1 (toffolis per bit · an enabling identity).

  • Toffolis: Same. 1 per swapped bit either way.
  • Qubits: Same. Unchanged.
  • Toffoli × qubit scores: Same. No gain alone; it exposes swaps to P02, P03, P13 and P17.
  • Q² × Toffoli (DQI): Same. Same.
from qiskit import QuantumCircuit

def before():
    c, a, b = 0, 1, 2
    qc = QuantumCircuit(3)
    qc.cswap(c, a, b)
    return qc
def after():
    c, a, b = 0, 1, 2
    qc = QuantumCircuit(3)
    qc.cx(b, a)
    qc.ccx(c, a, b)  # the one Toffoli inside a CSWAP
    qc.cx(b, a)
    return qc
NEEDS
Nothing
SEEN IN
Barrel shifters in the Kaggle 1/√x circuits
PROOF
QCP.P09.cswap_eq, any wires
P11 / CHEAPER BUILDING BLOCKS

Add or subtract under a control with one adder

A signed-digit multiplier or a modular step must compute b + a or b − a depending on a qubit s. Building a controlled adder and a controlled subtractor costs about two adders.

b − a equals NOT(NOT b + a). XOR s into every bit of b, run one ordinary adder, and XOR s in again. The control costs only CNOTs.

Before: Two controlled blocks, ≈2n. After: Complement, add, complement, ≈n (toffolis, n-bit add or subtract).

  • Toffolis: Lower. The second adder disappears: about 2 adders → 1.
  • Qubits: Same. Unchanged.
  • Toffoli × qubit scores: Lower. Halves each selected add/subtract.
  • Q² × Toffoli (DQI): Not applicable. Not seen in the public DQI decoders.
from qiskit import QuantumCircuit
from qiskit.circuit.library import ModularAdderGate
# b = b + a if s = 0, b - a if s = 1
S, A, B = 0, [1, 2, 3], [4, 5, 6]
ADD = ModularAdderGate(3)  # b += a (mod 8)

def before():
    qc = QuantumCircuit(7)
    qc.x(S)
    # controlled add
    qc.append(ADD.control(1), [S, *A, *B])
    qc.x(S)
    # controlled subtract
    qc.append(ADD.inverse().control(1), [S, *A, *B])
    return qc
def after():
    qc = QuantumCircuit(7)
    qc.cx(S, B)  # complement b when s = 1
    qc.append(ADD, [*A, *B])  # one plain adder
    qc.cx(S, B)  # NOT(NOT b + a) = b - a
    return qc
NEEDS
Nothing beyond the adder's own ancillas
SEEN IN
Signed-digit multiplier rows in Kaggle 1/√x generators
PROOF
QCP.P11.correct8, 8 bits
P14 / CHEAPER BUILDING BLOCKS

Table lookup by unary iteration

Loading T[address] from an L-entry classical table by testing each address separately costs a multi-controlled gate per entry.

Walk a binary tree of flags meaning "the address starts with this prefix". The flag for a 1-branch comes from the flag of its 0-branch sibling with a single CNOT (the sawtooth step shown here), and flags are erased by measurement.

Before: Rebuild the flag for each branch, L(n−1). After: Sawtooth: one CNOT to the next branch, L−2 (toffolis, l-entry table).

  • Toffolis: Lower. L(n−1) → L−2.
  • Qubits: Higher. One more flag qubit than the per-entry test.
  • Toffoli × qubit scores: Lower. A factor of about n−1 in Toffolis outweighs one qubit.
  • Q² × Toffoli (DQI): Lower. Still clearly lower.
from qiskit import QuantumCircuit

def before():
    p, a, flag = 0, 1, 2  # p = "prefix matches so far"
    qc = QuantumCircuit(3)
    # flag = p AND NOT a
    qc.x(a); qc.ccx(p, a, flag); qc.x(a)
    # ... load the entries of branch 0 ...
    # take the flag down
    qc.x(a); qc.ccx(p, a, flag); qc.x(a)
    qc.ccx(p, a, flag)  # rebuild it: flag = p AND a
    # ... load the entries of branch 1 ...
    return qc
def after():
    p, a, flag = 0, 1, 2
    qc = QuantumCircuit(3)
    # flag = p AND NOT a
    qc.x(a); qc.ccx(p, a, flag); qc.x(a)
    # ... load the entries of branch 0 ...
    qc.cx(p, flag)  # sawtooth: flag = p AND a
    # ... load the entries of branch 1 ...
    return qc
NEEDS
n−1 flag qubits for an n-bit address
SEEN IN
The standard lookup the Kaggle baselines start from (Babbush et al. 2018)
PROOF
QCP.P14.sawtooth (any wires) and .correct (8 entries)
P17 / CHEAPER BUILDING BLOCKS

Controlled swap into a wire known to be zero

A shift stage moves a bit into a neighbouring wire with a controlled swap and moves it back later: two Toffolis per bit.

If the destination is known to be zero, the swap is an AND into it followed by a CNOT. The way back is then a CNOT and a measured erase of that AND (P01), which is free.

Before: Swap out, swap back, 2. After: AND-move out, measured move back, 1 (toffolis per bit, round trip).

  • Toffolis: Lower. 2 → 1 per bit for the round trip.
  • Qubits: Same. Unchanged.
  • Toffoli × qubit scores: Lower. Lower on the 1/√x task, where shifts are about a tenth of the Toffolis.
  • Q² × Toffoli (DQI): Not applicable. Not seen in the public DQI decoders.
from qiskit import QuantumCircuit

def before():
    f, x, y = 0, 1, 2  # y is known to be 0
    qc = QuantumCircuit(3)
    qc.cswap(f, x, y)  # move x to y if f
    # ... use the shifted bits ...
    qc.cswap(f, x, y)  # move it back
    return qc
def after():
    f, x, y = 0, 1, 2
    qc = QuantumCircuit(3, 1)
    # same move, since y was 0
    qc.ccx(f, x, y); qc.cx(y, x)
    # ... use the shifted bits ...
    qc.cx(y, x)  # now y = f AND x again
    qc.h(y); qc.measure(y, 0); qc.reset(y)
    with qc.if_test((qc.clbits[0], 1)):
        qc.cz(f, x)
    return qc
NEEDS
The destination wire is zero on every input that can occur: a fact the generator must track
SEEN IN
Kaggle 1/√x barrel shifters (46 controlled swaps on the frontier)
PROOF
QCP.P17.move (any wires) and .roundTrip_correct
P18 / CHEAPER BUILDING BLOCKS

GF(8) inversion with 3 Toffolis and a free erase

The inverse in the 8-element field is x⁶ = x²·x⁴: one field product to compute it and one more to uncompute it.

Each output bit of the inverse is a polynomial of degree 2 in the input bits, so three Toffolis compute it directly, and an in-place form needs no output register. Because the degree is 2, the result is erased by measurement with Z and CZ repairs only.

Before: Inverse as a field product, 12. After: Degree-2 formulas, measured erase, 3 (toffolis, compute + erase).

  • Toffolis: Lower. 12 → 3 for compute plus erase.
  • Qubits: Lower. The in-place form saves the 3-qubit output register.
  • Toffoli × qubit scores: Lower. Both factors fall.
  • Q² × Toffoli (DQI): Lower. Inversion of GF(4096) is built on this leaf (66 Toffolis in public generators).
from qiskit import QuantumCircuit
# y = 1/x in GF(8), x^3 = x + 1
X, Y = [0, 1, 2], [3, 4, 5]

def inverse(qc):  # three degree-2 formulas
    qc.cx(X[0], Y[0]); qc.cx(X[1], Y[0]); qc.cx(X[2], Y[0])
    qc.ccx(X[1], X[2], Y[0])
    qc.cx(X[2], Y[1]); qc.ccx(X[0], X[1], Y[1])
    qc.cx(X[1], Y[2]); qc.cx(X[2], Y[2]); qc.ccx(X[0], X[2], Y[2])

def before():
    qc = QuantumCircuit(6)
    inverse(qc)
    # ... use y ...
    inverse(qc)  # uncompute: 3 more Toffolis
    return qc
def after():
    qc = QuantumCircuit(6, 3)
    inverse(qc)
    # ... use y ...
    for k in range(3):
        qc.h(Y[k]); qc.measure(Y[k], k); qc.reset(Y[k])
    with qc.if_test((qc.clbits[0], 1)):
        qc.z(X); qc.cz(X[1], X[2])
    with qc.if_test((qc.clbits[1], 1)):
        qc.z(X[2]); qc.cz(X[0], X[1])
    with qc.if_test((qc.clbits[2], 1)):
        qc.z(X[1]); qc.z(X[2]); qc.cz(X[0], X[2])
    return qc
NEEDS
Nothing. General rule: any register of degree ≤ 2 in live wires is erased for free
SEEN IN
Leaf of tower-field inversion in Kaggle DQI decoders
PROOF
QCP.P18.compute_correct, .erase_correct, .inPlace_correct
P20 / CHEAPER BUILDING BLOCKS

GF(8) multiplier with 6 Toffolis and no ancilla

Multiplying two 3-bit field elements term by term needs nine ANDs.

Six products of sums are enough: a₀c₀, a₁c₁, a₂c₂, (a₀+a₁)(c₀+c₁), (a₀+a₂)(c₀+c₂), (a₁+a₂)(c₁+c₂). Sums are formed in place with CNOTs and each product is delivered to its output bits by CNOT conjugation (P13). Six is the minimum.

Before: Schoolbook, 9. After: Karatsuba-style products of sums, 6 (toffolis per gf(8) product).

  • Toffolis: Lower. 9 → 6.
  • Qubits: Same. No ancilla in either form.
  • Toffoli × qubit scores: Lower. A third off every field product.
  • Q² × Toffoli (DQI): Lower. The DQI decoders are built from field products.
from qiskit import QuantumCircuit
# t ^= a * c in GF(8)
A, C, T = [0, 1, 2], [3, 4, 5], [6, 7, 8]

def before():  # one Toffoli per term
    qc = QuantumCircuit(9)
    for i, j, k in [(0, 0, 0), (0, 1, 1), (0, 2, 2), (1, 0, 1),
                    (1, 1, 2), (1, 2, 0), (1, 2, 1), (2, 0, 2),
                    (2, 1, 0), (2, 1, 1), (2, 2, 1), (2, 2, 2)]:
        qc.ccx(A[i], C[j], T[k])
    return qc
def after():  # six products of sums
    qc = QuantumCircuit(9)
    for bits, outs in [((0,), (0, 1, 2)), ((1,), (0, 2)), ((2,), (0,)),
                       ((0, 1), (1,)), ((0, 2), (2,)), ((1, 2), (0, 1))]:
        p, o = bits[0], outs[0]
        for q in bits[1:]:
            # sums in place
            qc.cx(A[q], A[p]); qc.cx(C[q], C[p])
        for r in outs[1:]:
            qc.cx(T[o], T[r])  # fan out
        qc.ccx(A[p], C[p], T[o])
        for r in outs[1:]:
            qc.cx(T[o], T[r])
        for q in bits[1:]:
            qc.cx(A[q], A[p]); qc.cx(C[q], C[p])
    return qc
NEEDS
Nothing; the target may hold data
SEEN IN
Leaf of the GF(4096) multiplier in Kaggle DQI: 7 × 6 = 42 Toffolis
PROOF
QCP.P20.correct, all inputs, dirty target
P21 / CHEAPER BUILDING BLOCKS

Load the difference of two tables

A register holds T[address] and should next hold T′[address]. Unloading one table and loading the other is two lookups.

Loading XORs data into the register, so a single lookup of the table T XOR T′ turns one into the other. Planners then order the loads so that the difference tables are cheap.

Before: Unload, then load, 2(L−2). After: One load of the difference, L−2 (toffolis, l-entry tables).

  • Toffolis: Lower. 2(L−2) → L−2.
  • Qubits: Same. Unchanged.
  • Toffoli × qubit scores: Lower. Loaders are over half the chemistry Toffolis.
  • Q² × Toffoli (DQI): Not applicable. Not seen in the public DQI decoders.
from qiskit import QuantumCircuit
# register holds T1[address]
T1, T2 = [2, 1, 3, 0], [1, 1, 0, 2]

def lookup(qc, table):  # reg ^= table[address]
    for i, word in enumerate(table):
        flip = [q for q in (0, 1) if not (i >> q) & 1]
        if flip: qc.x(flip)
        for j in (0, 1):
            if (word >> j) & 1:
                qc.ccx(0, 1, 2 + j)
        if flip: qc.x(flip)

def before():
    qc = QuantumCircuit(4)
    lookup(qc, T1)  # unload T1
    lookup(qc, T2)  # load T2
    return qc
def after():
    qc = QuantumCircuit(4)
    # one load
    lookup(qc, [x ^ y for x, y in zip(T1, T2)])
    return qc
NEEDS
The address is unchanged between the two loads
SEEN IN
Kaggle chemistry loaders: consecutive angle words
PROOF
QCP.P21.correct, 8 entries
P23 / CHEAPER BUILDING BLOCKS

Put the control on one operand

A product a·c should be added to the target only when a control qubit s is 1. Adding a control to every Toffoli of the multiplier roughly doubles it.

s·(a·c) equals (s·a)·c. Mask a with n temporary ANDs, run the plain multiplier on the masked copy, and erase the mask by measurement. The control can be injected wherever the data is narrowest.

Before: Control every Toffoli, ≈2r. After: Mask one operand, n + r (toffolis, controlled product of rank r).

  • Toffolis: Lower. About 2r → n + r (12 → 9 for GF(8)).
  • Qubits: Higher. n mask qubits during the product.
  • Toffoli × qubit scores: Depends. Lower if the mask fits under the peak width.
  • Q² × Toffoli (DQI): Depends. Check the peak first: here a qubit is worth twice as much.
from qiskit import QuantumCircuit
S, A, C, T, MASK = 0, [1, 2], [3, 4], [5, 6, 7], [8, 9]
# t ^= s * (a * c), carry-less 2 x 2 product

def before():
    qc = QuantumCircuit(10)
    for i in range(2):
        # every Toffoli gains a control
        for j in range(2):
            qc.mcx([S, A[i], C[j]], T[i + j])
    return qc
def after():
    qc = QuantumCircuit(10, 2)
    for i in range(2):
        qc.ccx(S, A[i], MASK[i])  # mask = s * a
    for i in range(2):
        for j in range(2):
            # plain multiplier
            qc.ccx(MASK[i], C[j], T[i + j])
    for i in range(2):
        qc.h(MASK[i]); qc.measure(MASK[i], i); qc.reset(MASK[i])
        with qc.if_test((qc.clbits[i], 1)):
            qc.cz(S, A[i])
    return qc
NEEDS
n clean qubits for the masked operand while the product runs
SEEN IN
Controlled products and reciprocals in Kaggle DQI decoders
PROOF
QCP.P23.correct, GF(8)
P26 / CHEAPER BUILDING BLOCKS

Controlled GF(8) inverse with a partial mask

A decoder needs y ^= c·inv(x): the inverse added to the target only when a control is 1. Composing P23 and P18 literally masks all three bits of x and then inverts the masked copy: six Toffolis and three helper qubits.

Mask only x₀ and x₁. The three remaining products are built so that the ones carrying x₂ also supply its linear terms, and they are written straight into the output. Two helpers are measured away with CZ repairs. A separate chained program reaches 4 Toffolis with 4 helpers, so the two forms trade width against gates.

Before: Mask everything, then invert, 6. After: Fused, partial mask, 5 (toffolis · helper qubits 3 → 2).

  • Toffolis: Lower. 6 → 5. The public chained form reaches 4.
  • Qubits: Lower. 3 → 2 helpers. The 4-AND form needs 4.
  • Toffoli × qubit scores: Lower. Block alone: 60 → 45 (the 4-AND form: 44).
  • Q² × Toffoli (DQI): Lower. Block alone: 600 → 405, ahead of the 4-AND form (484) when helpers set the peak.
from qiskit import QuantumCircuit
C, X, Y, H = 0, [1, 2, 3], [4, 5, 6], [7, 8, 9]
# y ^= c * (1/x) in GF(8)

def before():  # mask all of x, then invert
    qc = QuantumCircuit(10, 3)
    for i in range(3):
        qc.ccx(C, X[i], H[i])
    qc.cx(H, Y[0]); qc.ccx(H[1], H[2], Y[0])
    qc.cx(H[2], Y[1]); qc.ccx(H[0], H[1], Y[1])
    qc.cx(H[1], Y[2]); qc.cx(H[2], Y[2]); qc.ccx(H[0], H[2], Y[2])
    for i in range(3):
        qc.h(H[i]); qc.measure(H[i], i); qc.reset(H[i])
        with qc.if_test((qc.clbits[i], 1)):
            qc.cz(C, X[i])
    return qc
def after():  # mask x0 and x1 only
    u, v = H[0], H[1]
    qc = QuantumCircuit(10, 2)
    qc.ccx(C, X[0], u); qc.ccx(C, X[1], v)
    qc.cx(u, C); qc.ccx(X[2], C, Y[2]); qc.cx(u, C)
    qc.cx(v, C); qc.cx(Y[0], Y[1])
    qc.ccx(X[2], C, Y[0])
    qc.cx(Y[0], Y[1]); qc.cx(v, C)
    qc.cx(X[2], X[0]); qc.ccx(v, X[0], Y[1]); qc.cx(X[2], X[0])
    qc.cx(u, Y[0]); qc.cx(v, Y[0]); qc.cx(v, Y[2])
    for i, h in enumerate((u, v)):
        qc.h(h); qc.measure(h, i); qc.reset(h)
        with qc.if_test((qc.clbits[i], 1)):
            qc.cz(C, X[i])
    return qc
NEEDS
Two clean helpers; polynomial basis x³+x+1 with inv(0) = 0
SEEN IN
Found by search in our component research (R01). A public Kaggle generator has the 4-AND form
PROOF
QCP.P26.fused_correct and .fourAnd_correct, all inputs and records
08 / PART 4 · FEWER QUBITS

Sometimes the right move is to pay Toffolis for width.

Everything so far lowered the Toffoli count. The last four work on the other factor. They free a qubit earlier or never allocate a register, sometimes at a small Toffoli price.

Whether such a trade pays depends on two things: the scoreboard, and whether the block sits at the circuit's widest point. Below the peak, a spare qubit is free and the cheap-in-Toffolis form wins. At the peak, one qubit is worth the circuit's total Toffolis divided by its width, and twice that when qubits are squared.

P06 / FEWER QUBITS

Repair order and deferred repair

A scratch qubit u = a·b is needed only to make t = u·c. Keeping u alive until t has been used and removed holds a qubit for the whole stretch.

Free u at once by measurement. Later, t is erased by measurement too; its repair would need u, which is gone, so it becomes a conditional CCZ on a, b and c. That gate runs only when the outcome is 1, so it costs half a Toffoli on average. The repair can also be postponed until some wire holds the value again.

Before: u held until the end, 4. After: u freed before the use, 2.5 (mean toffolis · u is free during the use).

  • Toffolis: Lower. 4 → 2.5 on average in the animation.
  • Qubits: Lower. u is free during the use. In DQI decoders this frees whole 12-bit words early.
  • Toffoli × qubit scores: Lower. Both factors fall when the stretch sets the peak.
  • Q² × Toffoli (DQI): Lower. Qubits count twice here; a main reason the DQI forward pass is cheap.
from qiskit import QuantumCircuit

def before():  # d ^= a b c
    a, b, c, d, u, t = range(6)
    qc = QuantumCircuit(6)
    qc.ccx(a, b, u)
    qc.ccx(u, c, t)
    qc.cx(t, d)  # use t (u is held all along)
    qc.ccx(u, c, t)
    qc.ccx(a, b, u)
    return qc
def after():
    a, b, c, d, u, t = range(6)
    qc = QuantumCircuit(6, 2)
    qc.ccx(a, b, u)
    qc.ccx(u, c, t)
    # free u right away
    qc.h(u); qc.measure(u, 0); qc.reset(u)
    with qc.if_test((qc.clbits[0], 1)):
        qc.cz(a, b)
    qc.cx(t, d)  # use t; u is available to others
    qc.h(t); qc.measure(t, 1); qc.reset(t)
    with qc.if_test((qc.clbits[1], 1)):
        qc.ccz(a, b, c)  # runs half the time
    return qc
NEEDS
Classical bits kept until the repair; mean-executed gate counting for the half price
SEEN IN
Kaggle DQI frontier: about 200 words measured without repair in the forward pass
PROOF
QCP.P06.lateCubic_correct and .deferred_correct
P12 / FEWER QUBITS

In-place carries versus measured carries

The measured-carry adder of P04 is the cheapest in Toffolis but needs n−1 clean carry qubits. If the adder runs at the circuit's widest point, those qubits set the peak.

The Cuccaro adder stores each carry in the a register and needs one ancilla in total, at twice the Toffolis. Mixed forms hold k carries in place: k more Toffolis for k fewer qubits.

Before: n−1 carry qubits, n−1. After: 1 ancilla, 1 (ancilla qubits, n-bit adder · toffolis double).

  • Toffolis: Higher. +k Toffolis for k carries held in place (up to 2× the adder).
  • Qubits: Lower. −k qubits, down to one ancilla.
  • Toffoli × qubit scores: Depends. Pays only at the peak: one qubit is worth (total Toffolis ÷ peak qubits) Toffolis.
  • Q² × Toffoli (DQI): Depends. A qubit is worth twice as much: 886 Toffolis in the DQI frontier (measured).
from qiskit import QuantumCircuit
N = 3
A, B = [0, 1, 2], [3, 4, 5]  # b += a (mod 8)

def before():  # measured carries: N-1 ancillas
    c = [6, 7]
    qc = QuantumCircuit(8, N - 1)
    qc.ccx(A[0], B[0], c[0])
    for i in range(1, N - 1):
        qc.cx(c[i - 1], A[i]); qc.cx(c[i - 1], B[i])
        qc.ccx(A[i], B[i], c[i]); qc.cx(c[i - 1], c[i])
    qc.cx(c[N - 2], B[N - 1]); qc.cx(A[N - 1], B[N - 1])
    for i in range(N - 2, 0, -1):
        qc.cx(c[i - 1], c[i])
        qc.h(c[i]); qc.measure(c[i], i); qc.reset(c[i])
        with qc.if_test((qc.clbits[i], 1)):
            qc.cz(A[i], B[i])
        qc.cx(c[i - 1], A[i]); qc.cx(A[i], B[i])
    qc.h(c[0]); qc.measure(c[0], 0); qc.reset(c[0])
    with qc.if_test((qc.clbits[0], 1)):
        qc.cz(A[0], B[0])
    qc.cx(A[0], B[0])
    return qc
def after():  # Cuccaro: carries live in a
    z = 6  # the only ancilla
    qc = QuantumCircuit(8)
    chain = [z] + A
    for i in range(N - 1):  # MAJ
        qc.cx(A[i], B[i]); qc.cx(A[i], chain[i])
        qc.ccx(chain[i], B[i], A[i])
    qc.cx(A[N - 1], B[N - 1]); qc.cx(A[N - 2], B[N - 1])
    for i in range(N - 2, -1, -1):  # UMA
        qc.ccx(chain[i], B[i], A[i])
        qc.cx(A[i], chain[i]); qc.cx(chain[i], B[i])
    return qc
NEEDS
A decision per adder: is it at the peak width or below it?
SEEN IN
Kaggle 1/√x generators (carries kept in place for the low bits)
PROOF
QCP.P12.correct8 (Cuccaro) and QCP.P04.correct8
P19 / FEWER QUBITS

Erase an adder carry after its source is freed

A multiplier adds a row bit a = s₁·s₂ into an accumulator. The carry out of that position depends on a, so a is normally held until the carry has been erased.

Free a right after the forward step. When the carry is measured later, the missing term is s₁·s₂ times a bit that is still on a wire, so the repair is one conditional CCZ: half a Toffoli on average.

Before: a held across the higher bits, 2. After: a freed at once, 2.5 (mean toffolis · one qubit fewer held).

  • Toffolis: Higher. 2 → 2.5 on average per streamed position.
  • Qubits: Lower. −1 held product qubit per position.
  • Toffoli × qubit scores: Depends. Lower when the multiplier sets the peak, as in the 62-qubit 1/√x frontier.
  • Q² × Toffoli (DQI): Not applicable. Not seen in the public DQI decoders.
from qiskit import QuantumCircuit

def step(qc, a, b, c, d):  # b = a + b + c, d = carry out
    qc.cx(c, a); qc.cx(c, b)
    qc.ccx(a, b, d); qc.cx(c, d)
    qc.cx(c, a); qc.cx(a, b)

def before():  # a = s1 s2 is held to the end
    s1, s2, b, c, a, d = range(6)
    qc = QuantumCircuit(6, 2)
    qc.ccx(s1, s2, a)
    step(qc, a, b, c, d)
    # ... higher bits use d ...
    qc.cx(c, d); qc.cx(a, b); qc.cx(c, a)
    qc.h(d); qc.measure(d, 1); qc.reset(d)
    with qc.if_test((qc.clbits[1], 1)):
        qc.cz(a, b)  # needs a
    qc.cx(c, a); qc.cx(a, b)
    qc.h(a); qc.measure(a, 0); qc.reset(a)
    with qc.if_test((qc.clbits[0], 1)):
        qc.cz(s1, s2)
    return qc
def after():  # a is freed right after the step
    s1, s2, b, c, a, d = range(6)
    qc = QuantumCircuit(6, 2)
    qc.ccx(s1, s2, a)
    step(qc, a, b, c, d)
    qc.h(a); qc.measure(a, 0); qc.reset(a)
    with qc.if_test((qc.clbits[0], 1)):
        qc.cz(s1, s2)
    # ... higher bits use d; a's qubit is free ...
    qc.cx(c, d)
    qc.h(d); qc.measure(d, 1); qc.reset(d)
    with qc.if_test((qc.clbits[1], 1)):
        qc.cz(c, b)
        qc.cx(c, b); qc.x(b)
        qc.ccz(s1, s2, b)  # runs half the time
        qc.x(b); qc.cx(c, b)
    return qc
NEEDS
s₁, s₂, the carry-in and the sum bit unchanged; mean-executed counting
SEEN IN
Kaggle 1/√x generators (function phasefix in a public research dump)
PROOF
QCP.P19.correct, all inputs and records
P22 / FEWER QUBITS

Phase a shifted bit through one temporary qubit

A rotation must act on a bit of a register after a controlled shift. Shifting the whole register, rotating and shifting back costs two controlled swaps per bit and a full shifted copy.

A rotation only needs the value on some wire. Compute the selected bit z = r XOR f·(r XOR r′) onto one clean qubit with one Toffoli, rotate z, measure z, and repair the sign with Z and CZ. The same qubit serves every bit in turn.

Before: Swap, rotate, swap back, 2. After: Select onto z, rotate, measure, 1 (toffolis per phased bit).

  • Toffolis: Lower. 2 → 1 per phased bit and shift stage.
  • Qubits: Lower. No shifted copy of the register; one temporary qubit in total.
  • Toffoli × qubit scores: Lower. Both factors fall on the 1/√x task.
  • Q² × Toffoli (DQI): Not applicable. The DQI task allows no rotations.
from math import pi
from qiskit import QuantumCircuit
THETA = pi / 8

def before():  # rotate r if f = 0, r2 if f = 1
    f, r, r2 = 0, 1, 2
    qc = QuantumCircuit(4)
    qc.cswap(f, r, r2)
    qc.p(THETA, r)
    qc.cswap(f, r, r2)
    return qc
def after():
    f, r, r2, z = 0, 1, 2, 3
    qc = QuantumCircuit(4, 1)
    qc.cx(r, z)
    # z = the selected bit
    qc.cx(r2, r); qc.ccx(f, r, z); qc.cx(r2, r)
    qc.p(THETA, z)
    qc.h(z); qc.measure(z, 0); qc.reset(z)
    with qc.if_test((qc.clbits[0], 1)):
        qc.z(r)
        qc.cx(r2, r); qc.cz(f, r); qc.cx(r2, r)
    return qc
NEEDS
One clean qubit; the shift flag and both source bits unchanged during the step
SEEN IN
Kaggle 1/√x frontier (62 qubits): bit-serial phasing
PROOF
QCP.P22.correct, every rotation angle
09 / WHAT A PROOF BUYS

A test covers the inputs you tried. A proof covers the rest.

The contests check circuits on thousands of random inputs. That is strong evidence for a finished circuit, but it says nothing about the next size up, and rare inputs slip through: on one ecdsa.fail circuit we found that 92% of fresh runs fired some gate that 9,216 earlier runs never had.

FIG. 30 / LOOKING BACK: ALL 26, BY SHARE OF TOFFOLIS REMOVED AT THE SITE. HOVER A BAR.
SAVES TOFFOLISPAYS TOFFOLIS TO SAVE QUBITSIN READING ORDER · MEASURED AT A REPRESENTATIVE SIZE

Each pattern here is stated as a theorem instead. Eight hold for any wires in a circuit of any size. The rest are proved at a fixed size, for every input and every measurement outcome. Qubit counts are stated but not machine-checked: the Lean model counts Toffolis and the wires a block touches, not peak width.

The Kaggle paper itself closes by suggesting that future submissions "could pair a circuit generator with a proof of its correctness and cost". The next dispatch takes the patterns that are only proved at fixed sizes and proves them for all sizes.

ABOUT THE AUTHOR
SSiddharth LalwaniFOUNDER, ALMOND LABS
Siddharth Lalwani is a quantum computing enthusiast building at the edge of adoption: bringing NISQ-era quantum solutions into real enterprise workflows. He is Co-Founder and CEO of Skate and was previously a Venture Partner at Nomad Capital.
10 / SOURCES
01Scoring rule, validation checks and reference numbers for point addition: the ecdsa.fail challenge README and harness, Layr-Labs/ecdsafail-challenge.
02The three Kaggle benchmarks, their score formulas and the outlook on machine-checked proofs: Khattar, Rubin, Gidney, Broughton, Low and Babbush, Verifiable quantum circuit compilation, the paper distributed with the contest.
03Temporary AND and measured carries (P01, P04): Gidney, Halving the cost of quantum addition, Quantum 2, 74 (2018).
04Unary iteration (P14): Babbush, Gidney, Berry, Wiebe, McClean, Paler, Fowler and Neven, Encoding electronic spectra in quantum circuits with linear T complexity, arXiv:1805.03662.
05Measurement-based unlookup (P25): Berry, Gidney, Motzoi, McClean and Babbush, arXiv:1902.02134.
06In-place ripple-carry adder (P12): Cuccaro, Draper, Kutin and Moulton, arXiv:quant-ph/0410184.
07Constructions seen in the Kaggle contest (P05 to P08, P15 to P23, the 4-AND form in P26): public notebooks, write-ups and research dumps by contestants, including gluzdov, syed3000, maoxin123, gengsr, atakanaldemir, kirilltym, marculera and manwithacat, under Apache-2.0 or CC0 where a licence is stated. Figures quoted from them are their authors' claims.
08Measured ecdsa.fail figures in Part 2 and Section 09: our own scored submissions and replays on the public 651- and 652-qubit entries, 10 Nov 2026.
09Background for Sections 03 and 04: Gottesman, The Heisenberg representation of quantum computers (1998); Eastin and Knill, Restrictions on transversal encoded quantum gate sets (2009); Bravyi and Kitaev, Universal quantum computation with ideal Clifford gates and noisy ancillas (2005).
10Lean proofs, pattern cards and the tested Qiskit snippets for all 26 patterns: almond-lab/quantum-circuit-patterns.