In Deutsch’s problem the oracle was a perfect box. It flipped a target according to \(f\) and did nothing else. We also saw that a leftover bit which remembers the input destroys interference.
Real algorithms must build their oracles from gates, usually from an ordinary classical description of a function. An ordinary program stores intermediate results and later throws them away. A quantum circuit cannot throw anything away, and any intermediate result that remains is a which-path record. How can we evaluate a function on a superposition and leave behind only its value?
We start by writing down the contract a clean evaluation must meet. Translating classical logic into reversible gates meets that contract except for the intermediate results it leaves, so we remove them by running the computation backwards. The same construction gives phase oracles, and an experiment shows what is lost without it. Running backwards costs gates and the stored intermediates cost qubits, so we count both and learn to trade one for the other. Later algorithms will also reflect about prepared states and control whole subroutines, so we build these forms of access and find the global phase that control exposes.
With clean subroutines in hand, a function’s value can be kept as nothing but a sign, and signs are what the next technique reads.
How can a classical calculation become a reusable coherent subroutine?
Compute, copy the answer, uncompute: with that pattern, any classical function becomes a clean quantum oracle at about twice its classical cost.
Reading guide · preparation, aims, and assumptions
Build clean coherent subroutines: function evaluations and arithmetic that leave exactly the requested output, restore their workspace, and offer the inverse and controlled access later algorithms need.
Before you begin
Use the oracle contract, phase kickback, and which-path records from the Quantum Algorithmic Thinking chapter, and the reversible gates (NOT, CNOT, Toffoli) from Quantum Computing.
What you should be able to do
State the clean oracle contract and check whether a circuit satisfies it.
Translate a Boolean circuit into reversible gates and identify the garbage it leaves.
Apply compute–copy–uncompute and convert a clean evaluation into a phase oracle.
Explain with a calculation why garbage destroys interference.
Count gates and qubits, and trade time for space by recomputation.
Construct reflections and controlled versions from known circuits, and identify when these are extra assumptions.
The example to follow
The three-bit predicate f(a,b,c) = (a AND b) XOR c, built first with garbage, then cleanly by compute–copy–uncompute, then as a phase oracle tested by an interference experiment.
Scope and assumptions
Gates are ideal and the input is a basis-state superposition. Gate counts are construction bounds in a stated gate set, not lower bounds. Controlled access to an unknown black box is not assumed.
2.1
Reversible Evaluation
How do we turn an ordinary description of a function, such as a formula, a comparison or a piece of arithmetic, into a unitary? Logic gates like AND cannot be used as they stand, because a unitary loses no information and AND does. So we first say exactly what a finished evaluation may leave behind. Then we make each logic gate reversible and find that the translation leaves intermediate values behind. Arithmetic, which permutes basis states, then runs on superpositions without change.
Suppose a search procedure must recognize three-bit strings satisfying \(f(a,b,c)=(a\land b)\oplus c\). In an ordinary program we would compute \(g=a\land b\), combine it with \(c\), and throw \(g\) away. In a quantum algorithm, throwing away is not an operation we have. Worse, when we gave Deutsch’s circuit the target \(\ket0\), we saw that a leftover bit which depends on the input can silently destroy interference. So before building anything, we state precisely what the finished subroutine is allowed to leave behind.
For an \(n\)-bit input \(x\) and an \(m\)-bit value \(f(x)\), the clean oracle contract is
\[\ket{x}\ket{y}\ket{0^w}\longmapsto\ket{x}\ket{y\oplus f(x)}\ket{0^w}\quad\text{for every }x\in\{0,1\}^n,\ y\in\{0,1\}^m.\]
The three registers have distinct roles. The input \(x\) is preserved. The output target \(y\) may start in any state, and \(f(x)\) is added into it bit by bit with XOR. The workspace, \(w\) ancilla qubits used as scratch, must start in \(\ket{0^w}\) and must be returned to \(\ket{0^w}\). The equation must hold exactly, including phase, on every basis state. Once it does, linearity fixes the action on every superposition:
Slashes mark registers of \(n\), \(m\), and \(w\) qubits. The box may contain many gates and use the workspace freely, but it must return the workspace to \(\ket{0^w}\) on every basis input, with no input-dependent phase.
Why keep \(x\)? Because the naive map \(\ket{x}\mapsto\ket{f(x)}\) is not reversible whenever two inputs share a value: it would send two orthogonal states to the same state. Preserving \(x\) and adding into a separate target makes the map a permutation of basis states for every \(f\). Applying it twice restores \(y\), since \(y\oplus f(x)\oplus f(x)=y\).
Why insist on returning the workspace? Because the workspace is outside the contract’s promise to the caller. A caller who uses the oracle inside an interference experiment, as Deutsch’s algorithm did, needs the branches for different \(x\) to differ only in what the contract says. Any extra input-dependent record in the workspace would be a which-path record.
Problems
Write the clean contract for \(f(a,b)=a\land b\) with one output qubit and no workspace, and check that applying the map twice is the identity.
Show solutionHide solution
\(\ket{a}\ket{b}\ket{y}\mapsto\ket{a}\ket{b}\ket{y\oplus ab}\). Applying it twice gives \(y\oplus ab\oplus ab=y\). This is exactly the Toffoli gate.
An implementation of a predicate maps \(\ket{x}\ket{0}\ket{0}\mapsto\ket{x}\ket{f(x)}\ket{g(x)}\), where \(g\) is some intermediate value. For which functions \(g\) does it satisfy the clean contract with one ancilla?
Show solutionHide solution
Only when \(g(x)=0\) for every \(x\). The contract requires the ancilla to return to \(\ket0\) on every basis input. Even a constant \(g\equiv1\) violates it as stated, though in that special case a single \(X\) gate would repair it because the record carries no information about \(x\).
The contract demands that the map hold on all basis states with the stated phase. Give a map that sends every basis state \(\ket{x}\ket{y}\) to \(\ket{x}\ket{y\oplus f(x)}\) up to a phase \(e^{i\theta(x)}\) depending on \(x\), and explain why it does not satisfy the contract.
Show solutionHide solution
For example \(\ket{x}\ket{y}\mapsto(-1)^{x_1}\ket{x}\ket{y\oplus f(x)}\). On any single basis state it looks correct, since a phase on one basis state is unobservable. On a superposition of inputs, however, it multiplies different branches by different signs, which changes later interference: in the Deutsch circuit it would flip the answer whenever \(x_1\) differs between the two inputs. Relative phases between basis inputs are part of what a unitary does, so the contract fixes them.
2.1.2 From Boolean circuits to reversible circuits§
How do we build a clean oracle from an ordinary description of \(f\)? Any Boolean function has a circuit of AND, OR, and NOT gates. NOT is already reversible. AND is not: three of its four inputs give output \(0\). The Toffoli gate fixes this by keeping both inputs and adding the AND into a target,
With \(t=0\), the target becomes \(ab\). OR follows from De Morgan’s law, \(a\lor b=\lnot(\lnot a\land\lnot b)\), so it costs a Toffoli and some \(X\) gates. XOR into an existing bit is a CNOT. So translate the circuit gate by gate: every AND or OR gets a fresh ancilla initialized to \(0\) as its target.
The translation works, but it leaves a trail. Every intermediate gate value now sits in its own ancilla. For our predicate \(f=(a\land b)\oplus c\), a direct translation computes \(g=ab\) into one ancilla, then \(t=g\oplus c\) into another:
A Toffoli computes \(g=a\land b\); two CNOTs compute \(t=g\oplus c\). The answer \(t=f(a,b,c)\) is accompanied by the input-dependent garbage bit \(g\).
The final values \((a,b,c,g,t)=(a,b,c,ab,f(a,b,c))\) contain the answer, but also the intermediate value \(ab\). That extra, input-dependent data is called garbage. In a classical computer garbage is merely wasteful; it can be overwritten later. In a quantum computer garbage is a which-path record that prevents the branches it distinguishes from interfering.
A word on size. If the original circuit has \(G\) AND/OR gates, the direct translation uses \(G\) Toffolis and up to \(G\) ancillas, plus \(X\) and CNOT gates. The number of qubits can therefore grow with the running time of the classical computation, not just with its memory.
Problems
Construct \(a\lor b\) into a fresh ancilla using one Toffoli and \(X\) gates, restoring \(a\) and \(b\) afterwards.
Show solutionHide solution
Apply \(X\) to \(a\) and \(b\), Toffoli into the ancilla (now holding \(\bar a\bar b\)), \(X\) on the ancilla (now \(1\oplus\bar a\bar b=a\lor b\)), and \(X\) on \(a\) and \(b\) again to restore them. Five \(X\) gates and one Toffoli.
Translate \(f(a,b,c)=(a\land b)\lor c\) directly into reversible gates. How many ancillas and Toffolis does the direct translation use, and what garbage remains?
Show solutionHide solution
One Toffoli computes \(g=ab\) into ancilla 1. The OR \(g\lor c\) uses a second Toffoli (with \(X\) gates on \(g\) and \(c\) around it) into ancilla 2, followed by \(X\) on ancilla 2. Two ancillas, two Toffolis. Ancilla 2 holds \(f\); ancilla 1 holds the garbage \(ab\).
Why can we not simply apply a “reset to \(0\)” operation to the garbage ancilla at the end of the circuit?
Show solutionHide solution
Reset is not unitary: it maps both \(\ket0\) and \(\ket1\) to \(\ket0\). Physically it can be done by measuring and flipping, but measuring the garbage collapses the input superposition onto inputs consistent with the outcome, and discarding it without measuring leaves the input entangled with the environment. Either way the coherent superposition the algorithm needs is destroyed. Garbage must be removed reversibly.
Can the reversible translation do arithmetic on a superposition of numbers? A reversible circuit applies the same gate sequence to every basis component, so a classical reversible computation becomes a quantum one by linearity. Reversible arithmetic is the case we will need most: phase estimation, period finding, and amplitude estimation all use it.
Start with incrementing a two-bit register \(\ket{b_1b_0}\), where \(b_1\) is the high bit. Apply a CNOT from \(b_0\) to \(b_1\), then an \(X\) on \(b_0\). The CNOT flips the high bit exactly when the low bit is \(1\), which is when adding one produces a carry; the \(X\) then flips the low bit. Check all four inputs:
This is modular addition: adding one modulo four. The word modulo specifies what happens on overflow: \(3+1\) wraps to \(0\) rather than needing a third bit. That wrap-around is what makes the map a permutation, and hence reversible.
The high bit \(b_1\) is drawn first. The CNOT adds the carry from the low bit; the \(X\) flips the low bit. The map is \(0\to1\to2\to3\to0\), a permutation, so it acts on superpositions without measurement.
On a superposition, nothing new is needed: \((\ket{00}+i\ket{11})/\sqrt2\mapsto(\ket{01}+i\ket{00})/\sqrt2\). No measurement, no classical branching. Reversing the gate order gives the inverse, subtraction of one.
The \(n\)-bit incrementer follows the same idea. Process target bits from highest to lowest: flip bit \(j\) if all lower bits are \(1\), then finally flip bit \(0\). Descending order matters, because each controlled flip reads the lower bits before they change. Bit \(j\) needs a \(j\)-controlled \(X\), which is not an elementary gate; with one or more ancillas it decomposes into \(O(j)\) Toffolis, so the whole incrementer costs \(O(n^2)\) Toffolis this way, and more careful constructions reach \(O(n)\). More generally, reversible adders computing \(\ket{a}\ket{b}\mapsto\ket{a}\ket{a+b\bmod2^n}\) are known with \(O(n)\) Toffoli and CNOT gates and one ancilla, for example the ripple-carry adder of Cuccaro, Draper, Kutin, and Moulton (2004). Modular multiplication and exponentiation, built from repeated addition, are the dominant cost of Shor’s factoring algorithm.
Problems
Apply the two-bit incrementer to \(\frac12(\ket{00}+\ket{01}+\ket{10}+\ket{11})\). What changes?
Show solutionHide solution
Each basis state maps to the next one mod 4, so the uniform superposition maps to itself. A permutation of basis states leaves the uniform superposition invariant; its effect becomes visible only on nonuniform amplitudes or phases.
Reverse the two gates of the incrementer (first \(X\) on \(b_0\), then CNOT from \(b_0\) to \(b_1\)). What map results?
Show solutionHide solution
\(00\to01\to11\), \(01\to00\to00\), \(10\to11\to01\), \(11\to10\to10\). That is \(0\to3\), \(1\to0\), \(2\to1\), \(3\to2\): subtraction of one mod 4. Each gate is self-inverse, but their ordered product is not, and reversing the order inverts it.
Write a gate sequence for a three-bit incrementer using Toffoli, CNOT, and \(X\), and verify it on input \(011\).
Show solutionHide solution
Toffoli with controls \(b_1,b_0\) targeting \(b_2\); CNOT from \(b_0\) to \(b_1\); \(X\) on \(b_0\). On \(011\): the Toffoli sees \(b_1=b_0=1\) and flips \(b_2\), giving \(111\); the CNOT flips \(b_1\), giving \(101\); the \(X\) flips \(b_0\), giving \(100\). That is \(3+1=4\). Doing the CNOT before the Toffoli would be wrong: \(b_1\) would already be changed when the Toffoli reads it.
2.2
Workspace Management
The direct translation leaves garbage. Can we simply erase it? Measuring or resetting a garbage bit leaves behind a record of its value, in the measurement result or in the environment, so the branches it distinguished still cannot interfere. The way out, found for classical reversible computing before quantum computing existed, is to copy the answer and then run the computation backwards. Once that works, the same pattern turns a computed bit into a sign. Comparing a clean run with a dirty one then shows exactly what the backward pass buys.
Let \(C\) be the garbage-producing direct translation of our predicate: Toffoli from \(a,b\) into \(g\), CNOT from \(g\) into \(t\), CNOT from \(c\) into \(t\). Afterwards \(g=ab\) and \(t=f(a,b,c)\). Now do three things.
Compute: apply \(C\).
Copy: CNOT from \(t\) into the external target \(y\).
Uncompute: apply \(C^{-1}\), the gates of \(C\) in reverse order (each is its own inverse).
Register order \(a,b,c,g,t,y\). The first three gates compute \(g=ab\) and \(t=f\); one CNOT copies \(t\) into the external target \(y\); the last three gates are the first three in reverse order, returning \(g\) and \(t\) to \(\ket0\).
For a basis input \(x=(a,b,c)\), with register order \((x,g,t,y)\),
Why does the last step clear the workspace without disturbing \(y\)? Because \(C^{-1}\) does not touch \(y\), and the registers it does touch, \((x,g,t)\), are exactly as \(C\) left them: the copy only read \(t\). Undoing \(C\) on its own output returns its own input, \((x,0,0)\). The input \(x\) is what makes this possible, since it still contains everything needed to recompute and hence un-recompute the intermediate values.
Figure guide. The figure shows the compute–copy–uncompute circuit acting on input superposition \((\ket{000}+\ket{110})/\sqrt2\) with workspace and output registers initialized to \(g=t=y=0\). Trace the joint state after the CNOT copy step and after the reversed computation \(U_{\mathrm{compute}}^\dagger\) to see how the workspace disentangles.
What to observe
The inputs have \(f=0\) and \(f=1\). After compute and copy: \(\frac{1}{\sqrt2}(\ket{000}\ket0\ket0\ket0+\ket{110}\ket1\ket1\ket1)\). After uncomputation: \(\frac{1}{\sqrt2}(\ket{000}\ket0\ket0\ket0+\ket{110}\ket0\ket0\ket1)\). The workspace now factors out as \(\ket{00}\); only the requested output still distinguishes the branches.
This compute–copy–uncompute pattern is due to Bennett, Logical Reversibility of Computation (1973), who used it to show that any classical computation can be made reversible without accumulating garbage. Nothing in the argument depends on the input being a basis state, so by linearity it gives a clean quantum oracle. Notice what is not cleared: the output target still records \(f(x)\). Uncomputation removes everything the contract did not ask for and nothing it did.
Problems
Trace the six registers through the circuit for input \(x=111\), \(y=0\).
Show solutionHide solution
Compute: \(g=1\), then \(t=g\oplus c=0\). So \(f(111)=0\) and the state is \(\ket{111,1,0,0}\). Copy: \(y=0\). Uncompute: \(t\leftarrow t\oplus c=1\), \(t\leftarrow t\oplus g=0\), \(g\leftarrow g\oplus ab=0\). Final \(\ket{111,0,0,0}\), matching \(f(111)=0\).
Count the gates in compute–copy–uncompute for this predicate and compare with the direct construction (Toffoli into \(y\), then CNOT from \(c\) into \(y\)).
Show solutionHide solution
Compute–copy–uncompute: 2 Toffolis and 5 CNOTs on 6 qubits. Direct: 1 Toffoli and 1 CNOT on 4 qubits. Both satisfy the clean contract. The pattern is a general method that always works, not an optimal construction for every function.
Does the copying CNOT violate the no-cloning theorem? Consider its action on \(\alpha\ket0+\beta\ket1\) in the \(t\) register.
Show solutionHide solution
No. On \(\alpha\ket0+\beta\ket1\) with target \(\ket0\) it produces \(\alpha\ket{00}+\beta\ket{11}\), not \((\alpha\ket0+\beta\ket1)\otimes(\alpha\ket0+\beta\ket1)\). It copies basis values, creating correlation, not independent copies of an arbitrary state. That is exactly what the contract asks for: a coherent record of the classical value \(f(x)\) in each branch.
Deutsch’s circuit used the phase oracle \(\ket{x}\mapsto(-1)^{f(x)}\ket{x}\). Can a clean evaluation supply it? It can, at no extra cost: initialize the external target in \(\ket-\). The copy step is then a CNOT into \(\ket-\), which multiplies by \((-1)^{t}\) and leaves the target in \(\ket-\). After uncomputation,
Both the workspace and the target factor out, unchanged. On the two-input example, \((\ket{000}+\ket{110})/\sqrt2\) becomes \((\ket{000}-\ket{110})/\sqrt2\). The sign is now a relative phase between input branches, available to later interference, with nothing else distinguishing them.
There is a slightly cheaper variant. Instead of copying into a \(\ket-\) target, apply a \(Z\) gate to \(t\) directly: \(Z\ket{t}=(-1)^t\ket t\). Then uncompute. This saves the target qubit. For multi-bit outputs, a phase \(e^{i\phi(v)}\) depending on a computed value \(v\) can be applied by phase gates on the bits of \(v\); we build this when we study phase encoding.
\(C\) computes \(f(x)\) into the qubit \(t\) together with garbage in the workspace. A \(Z\) on \(t\) multiplies by \((-1)^{f(x)}\); \(C^{-1}\) then clears both \(t\) and the workspace, leaving only the sign on the input.
Either way, the phase oracle costs about twice the gates of computing \(f\), since the computation runs forwards and backwards. Counting a phase query as “one query” in an algorithm’s analysis is legitimate in the oracle model; in a gate count, each such query costs a compute and an uncompute.
Problems
Verify the \(Z\)-variant on input \(110\): compute, apply \(Z\) to \(t\), uncompute. What phase appears?
Show solutionHide solution
Compute gives \(g=1\), \(t=1\oplus0=1\). \(Z\) on \(t\) gives a factor \(-1\). Uncompute restores \(g=t=0\). The result is \(-\ket{110}\ket{00}\), matching \((-1)^{f(110)}=-1\).
For a two-bit computed value \(v=2v_1+v_0\), give phase gates that apply \(e^{2\pi iv/4}\) before uncomputation.
Show solutionHide solution
\(e^{2\pi iv/4}=e^{i\pi v_1}e^{i\pi v_0/2}\). Apply \(Z\) to \(v_1\) and \(S=\mathrm{diag}(1,i)\) to \(v_0\), then uncompute. Check: \(v=3\) gives \((-1)\cdot i=-i=e^{2\pi i\cdot3/4}\).
A student applies \(Z\) to the garbage bit \(g=ab\) instead of \(t\), then uncomputes. What oracle is implemented, and could it ever be useful?
Show solutionHide solution
The phase is \((-1)^{ab}\), a phase oracle for \(a\land b\) rather than for \(f\). It is a perfectly clean operation, just for a different function. Any intermediate value can be turned into a phase; the error is only in which one. This flexibility is useful: algorithms often need phases of intermediate quantities.
How much does a skipped uncomputation actually cost? We can test it with an experiment that distinguishes a clean oracle from a dirty oracle, one that leaves garbage behind. Prepare the input \((\ket{000}+\ket{110})/\sqrt2\) and run the phase-oracle construction twice: once with uncomputation, once without.
Clean. The input becomes \((\ket{000}-\ket{110})/\sqrt2\), with workspace \(\ket{00}\). Now apply a CNOT from the first input bit to the second, giving \((\ket{000}-\ket{100})/\sqrt2=\ket-\ket{00}\), and a Hadamard on the first bit. The first bit becomes \(\ket1\) with certainty.
Dirty. Without uncomputation the state is \((\ket{000}\ket{00}-\ket{110}\ket{11})/\sqrt2\). The same CNOT gives \((\ket{000}\ket{00}-\ket{100}\ket{11})/\sqrt2\). The two branches now differ in the workspace, \(\ket{00}\) versus \(\ket{11}\). The Hadamard on the first bit produces amplitudes \(\pm\frac12\) on four distinct complete configurations, and nothing cancels: the first bit is a fair coin.
Input \((\ket{000}+\ket{110})/\sqrt2\); apply the phase oracle, then a CNOT from the first input bit to the second and a Hadamard on the first. Columns show input register and workspace.
Why can no later gate on the input repair this? Any operation on the input acts separately on the two workspace branches, \(\ket{00}\) and \(\ket{11}\). Those branches are orthogonal, so every outcome probability is the sum of the two branches’ probabilities, never the square of a summed amplitude. The input therefore behaves exactly like a mixture: \(\ket{000}\) with probability \(1/2\) and \(-\ket{110}\) with probability \(1/2\), as if a coin had chosen one of them. The relative sign that the algorithm worked to create is no longer accessible to any operation on the input alone. Garbage behaves exactly like an environment that has measured the branch. This is why every oracle in the rest of the course is assumed clean, and why constructing one costs uncomputation.
Problems
In the dirty case, compute the probability that the first input bit reads \(0\) after the CNOT and Hadamard, by listing the final amplitudes.
Show solutionHide solution
After the CNOT, \((\ket{0}\ket{00}\ket{00}-\ket{1}\ket{00}\ket{11})/\sqrt2\) (first bit, other input bits, workspace). The Hadamard gives \(\frac12(\ket0+\ket1)\ket{00}\ket{00}-\frac12(\ket0-\ket1)\ket{00}\ket{11}\). The first bit is \(0\) with amplitudes \(\frac12\) (workspace \(00\)) and \(-\frac12\) (workspace \(11\)) on different configurations, so the probability is \(\frac14+\frac14=\frac12\).
Suppose the garbage happened to be the same for both inputs, for instance \(g(x)=0\) on both. Would the dirty oracle still fail the test?
Show solutionHide solution
No. If the workspace is identical on both branches, it factors out and interference proceeds as in the clean case. Garbage is harmful precisely to the extent that it distinguishes branches meant to interfere. A rigorous contract demands all-zero workspace because the oracle’s caller cannot know which branches will be combined.
Could a later step “fix” the dirty state by applying \(C^{-1}\) after the Hadamard instead of before it?
Show solutionHide solution
Not in general. \(C^{-1}\) is correct only when applied to registers in the state \(C\) produced. The Hadamard and CNOT have changed the input bits, so \(C^{-1}\) now reads different controls and does not clear the workspace. The order matters: uncompute while the inputs are still as the computation left them, then interfere.
2.3
Costs and Tradeoffs
Clean evaluation always works, but what does it cost? It runs the computation twice, and the direct translation keeps one ancilla for every gate. So we first count gates and qubits, in the units that matter on fault-tolerant hardware. Then we ask whether intermediate values can be cleared early, so that fewer qubits suffice in exchange for more gates.
How many gates does compute–copy–uncompute use? Suppose a reversible circuit \(C\) uses \(G\) gates, preserves its input, and computes an \(m\)-bit answer together with garbage. Then the gate count of the clean oracle is
using the same workspace as \(C\) plus an \(m\)-qubit target. This is a construction bound, not a lower bound; clever circuits often do better. But it is a uniform bound: whatever classical algorithm computes \(f\) in \(G\) reversible gates, a clean quantum oracle costs about \(2G\).
What counts as one gate? In fault-tolerant quantum computers, the expensive operation is usually the \(T\) gate, \(T=\mathrm{diag}(1,e^{i\pi/4})\), not the CNOT. A Toffoli is not elementary there. The standard textbook decomposition (Nielsen and Chuang, Quantum Computation and Quantum Information, Section 4.3) uses six CNOTs and seven \(T\) or \(T^\dagger\) gates, together with two Hadamards. So a resource estimate might report Toffoli count or \(T\) count separately from CNOT count and depth. Multi-controlled gates must also be decomposed: a \(k\)-controlled \(X\) needs on the order of \(k\) Toffolis with \(k-2\) clean ancillas (Barenco et al., 1995).
Typical constructions in the Clifford+\(T\) gate set. Counts are for standard textbook circuits and can be reduced in context, for example when a Toffoli is later uncomputed.
The lesson for reading algorithm papers is to check the unit. “\(O(n^2)\) gates” might count Toffolis, two-qubit gates, or \(T\) gates, and the conversions between them are constant factors that can be large in practice. A box in a circuit diagram labelled “\(U_f\)” or “modular exponentiation” might contain millions of elementary gates.
Problems
A classical reversible circuit for \(f\) uses 1000 Toffolis and 3000 CNOTs and outputs 16 bits. Estimate the Toffoli and CNOT counts of a clean oracle built by compute–copy–uncompute.
Show solutionHide solution
2000 Toffolis and \(6000+16=6016\) CNOTs. As a phase oracle via \(Z\) gates on a one-bit output, the copy step is replaced by one \(Z\); the counts are then 2000 Toffolis and 6000 CNOTs.
Using the decomposition above, convert 2000 Toffolis into \(T\)-gate and CNOT counts.
Show solutionHide solution
\(7\times2000=14{,}000\) \(T\)/\(T^\dagger\) gates and \(6\times2000=12{,}000\) additional CNOTs (plus 4000 Hadamards). Better decompositions exist for Toffolis that are later uncomputed, since a Toffoli followed by its inverse can share work; this is one reason exact counts depend on the construction.
Two papers report “\(10^6\) gates” and “\(10^5\) gates” for the same oracle. What questions must you ask before concluding the second is ten times cheaper?
Show solutionHide solution
Which gate set each counts (Clifford+\(T\), Toffoli+CNOT, arbitrary two-qubit gates), whether the counts include uncomputation, how many qubits each uses (a time–space tradeoff may explain the difference), whether depth or count is reported, and whether both implement the same contract (clean versus leaving garbage, exact versus approximate arithmetic).
The direct translation keeps every intermediate value until the end, so its workspace grows with the number of gates. For a long computation that is prohibitive. Can we free intermediate values earlier, and what must we pay to do so?
Consider a computation in stages: \(u_1=F_1(x)\), \(u_2=F_2(u_1)\), \(u_3=F_3(u_2)\), and so on up to \(u_k\). To compute \(u_3\) we need \(u_2\), but once \(u_3\) exists, \(u_2\) could be uncomputed, provided \(u_1\) is still present, because uncomputing \(u_2=F_2(u_1)\) requires \(u_1\). Then, to clear \(u_1\) later, we need \(x\). Clearing a value early saves space, but if a later uncomputation needs it, we must recompute it, which costs time. This is a time–space tradeoff.
This bookkeeping is a game called pebbling. Place a pebble on stage \(i\) (compute \(u_i\)) only if stage \(i-1\) has a pebble; remove it (uncompute) under the same condition. The goal is to end with pebbles on \(x\) and \(u_k\) only. Keeping everything uses \(k\) pebbles and \(2k-1\) moves: \(k\) forward, then \(k-1\) back, since \(u_k\) stays. Can we hold fewer pebbles? Try recursion. To reach stage \(k\), pebble stage \(k/2\), use it as a new starting point to pebble \(k\), then unpebble \(k/2\) by running the first half backwards. Each of the three steps is a half-length problem. So if \(c(k)\) is the number of moves, \(c(k)=3c(k/2)\) with \(c(1)=1\), which gives \(c(k)=3^{\log_2k}=k^{\log_23}\approx k^{1.58}\). The pebbles needed grow by one per level, the one left on \(k/2\) while the second half runs, so about \(\log_2k+1\) pebbles suffice. For \(k=4\) that is \(9\) moves and \(3\) pebbles, against \(7\) moves and \(4\) pebbles.
For a chain of \(k\) stages, each computed from the previous one. A pebble is a stored intermediate value. The recursive strategy holds fewer values at once but recomputes some of them.
Splitting into more than two pieces per level lowers the exponent further. Bennett proved in 1989, as a quoted result, that a computation using time \(t\) and space \(s\) can be made reversible in time \(O(t^{1+\epsilon})\) and space \(O(s\log t)\) for any fixed \(\epsilon>0\) (Bennett, Time/Space Trade-Offs for Reversible Computation). Practical quantum compilers use similar schedules, choosing when to uncompute to fit within a qubit budget. The central constraint is always the same: a value can be uncomputed only while the values it was computed from are still present, and the operations between compute and uncompute must leave those values unchanged.
Problems
For a chain of \(k=4\) stages, give a pebbling that ends with pebbles only on \(u_4\) (besides \(x\)) and never uses more than three pebbles at once. Compare with keeping everything.
Show solutionHide solution
Write \(+i\) for computing \(u_i\) and \(-i\) for uncomputing it. The sequence \(+1,+2,-1,+3,+4,-3,+1,-2,-1\) is valid: each move on stage \(i\) happens while stage \(i-1\) (or \(x\), for \(i=1\)) holds a pebble. The pebble sets are \[\{1\},\{1,2\},\{2\},\{2,3\},\{2,3,4\},\{2,4\},\{1,2,4\},\{1,4\},\{4\}\]: at most three, in 9 moves. Keeping everything uses four pebbles and 7 moves (\(+1,+2,+3,+4,-3,-2,-1\)). A search over all schedules shows that two pebbles cannot reach stage 4 at all.
In the incorrect sequence “CNOT \(x\to g\); \(X\) on \(x\); CNOT \(x\to g\)”, intended to compute and then uncompute \(g=x\), what is left in \(g\)?
Show solutionHide solution
After the first CNOT, \(g=x\). After the flip, the input is \(x\oplus1\). The second CNOT gives \(g=x\oplus(x\oplus1)=1\), not \(0\). The operation between compute and uncompute changed the value the uncomputation depends on.
Why is the recursive pebbling strategy more important for quantum computers than for classical reversible hardware?
Show solutionHide solution
Qubits are a scarce resource: early fault-tolerant machines will have limited numbers of logical qubits, each costing many physical qubits. Classical computers can simply erase garbage at an energy cost, so they rarely need reversibility at all. A quantum computer must stay reversible to preserve coherence, so the space cost of garbage is unavoidable unless traded for time.
2.4
Algorithmic Access
So far a subroutine only runs forwards. Later algorithms will reflect about prepared states, apply controlled powers of a unitary, and pass states on to other routines. Which of these can we build from a known gate sequence, and what does each cost? Running a preparation backwards gives reflections. Controlling every gate gives controlled versions, but it exposes the global phase. Finally, the state a subroutine leaves is useful only if the next step can extract something from it.
Suppose a later algorithm needs to reflect about a state \(\ket\psi\). What must we have besides \(\ket\psi\) itself? Let a preparation circuit \(A\) be a unitary with \(A\ket{0^n}=\ket\psi\). If its gates are known, reversing their order and inverting each gives \(A^\dagger\), which maps \(\ket\psi\) back to \(\ket{0^n}\). A supplied copy of \(\ket\psi\) does not give us this; neither does a box that applies \(A\) but cannot be run backwards.
Why do we want \(A^\dagger\)? Because it lets us reflect about \(\ket\psi\). Let \(S_0=2\ket{0^n}\bra{0^n}-I\), which leaves \(\ket{0^n}\) unchanged and negates every orthogonal basis state. Then
\[R_\psi=A\,S_0\,A^\dagger=2\ket\psi\bra\psi-I.\]
Check on two kinds of input. On \(\ket\psi\): \(A^\dagger\) sends it to \(\ket{0^n}\), \(S_0\) leaves it, \(A\) restores \(\ket\psi\). On a state \(\ket\phi\) orthogonal to \(\ket\psi\): \(A^\dagger\ket\phi\) is orthogonal to \(\ket{0^n}\), because \(A^\dagger\) preserves inner products, so \(S_0\) negates it and \(A\) returns \(-\ket\phi\). A reflection about \(\ket\psi\) is exactly the map that fixes \(\ket\psi\) and negates everything orthogonal to it.
Top: \(R_\psi=A S_0 A^\dagger\) with \(A\ket{0^n}=\ket\psi\); the matrix product is read right to left, the circuit left to right. Bottom: one construction of \(S_0\) on three qubits, up to a global sign: \(X\) on every qubit, a doubly controlled \(Z\), and \(X\) again.
The zero-state reflection \(S_0\) itself is a clean phase oracle for the predicate “\(x\neq0^n\)”: it is \(-\)(phase oracle of \(x=0^n\)), which differs by a global sign. With \(X\) gates on every qubit and an \(n\)-controlled \(Z\), it costs \(O(n)\) Toffolis. Amplitude amplification will use \(R_\psi\) to raise success probabilities, at the cost of one \(A\) and one \(A^\dagger\) per reflection.
Problems
For one qubit with \(A=H\), compute \(R_\psi=HS_0H\) as a matrix and identify it.
Show solutionHide solution
\(S_0=\mathrm{diag}(1,-1)=Z\), so \(R_\psi=HZH=X\). Indeed \(X\) fixes \(\ket+\) and negates \(\ket-\): it is the reflection about \(\ket+\).
Show that \(R_\psi^2=I\) and that \(R_\psi\) is Hermitian.
Show solutionHide solution
\(R_\psi^2=4\ket\psi\braket{\psi}{\psi}\bra\psi-4\ket\psi\bra\psi+I=I\), using \(\braket\psi\psi=1\). And \((2\ket\psi\bra\psi-I)^\dagger=2\ket\psi\bra\psi-I\). Reflections are self-inverse, as geometric intuition suggests.
Someone has a box \(B\) that outputs fresh copies of \(\ket\psi\) on demand, but no circuit for it. Can they implement \(R_\psi\) exactly?
Show solutionHide solution
Not with the construction above, which needs \(A^\dagger\). With copies alone one can approximate \(e^{-i\ket\psi\bra\psi t}\) using many copies (a technique called density-matrix exponentiation), but not cheaply implement an exact reflection. Copies and a preparation circuit are different forms of access, and the algorithm must state which it assumes.
Given a gate sequence \(U=G_k\cdots G_1\), we can build \(\mathrm{C}U\) by controlling each gate: \(\mathrm{C}U=\mathrm{C}G_k\cdots\mathrm{C}G_1\). This works because on the control-\(0\) branch every controlled gate does nothing, and on the control-\(1\) branch every one acts. A controlled single-qubit gate costs a few CNOTs and rotations; a controlled Toffoli is a three-controlled \(X\), and so on. So controlling a circuit multiplies its cost by a constant.
If \(U=G_2G_1\), then controlled-\(U\) is controlled-\(G_1\) followed by controlled-\(G_2\). On the control-0 branch nothing acts; on the control-1 branch both gates act. The global phase of \(U\) must be fixed first, because it becomes a phase on the control.
There is one subtlety. Uncontrolled, \(U\) and \(e^{i\theta}U\) are the same physical operation. Controlled, they differ: \(\mathrm{C}(e^{i\theta}U)=\mathrm{C}U\cdot(P(\theta)\otimes I)\), where \(P(\theta)=\mathrm{diag}(1,e^{i\theta})\) on the control. The global phase of \(U\) becomes a relative phase on the control. In phase estimation, that phase is exactly what is measured. So a controlled version is defined only once the global phase of \(U\) is fixed. A gate library that implements rotations “up to global phase” must be checked before its gates are controlled.
For a sealed box \(U\), no general procedure produces \(\mathrm{C}U\). This is a theorem, not a gap in our cleverness: given only black-box access to an unknown unitary, no circuit implements its controlled version, essentially because the box cannot reveal its own global phase (Araújo, Feix, Costa, and Brukner, 2014). Algorithms that need \(\mathrm{C}U\) must assume it as access, or construct \(U\) from known gates.
Problems
Show that \(\mathrm{C}(-I)=Z\otimes I\) on a control and one target qubit.
Show solutionHide solution
On control \(0\) nothing happens; on control \(1\) the target is multiplied by \(-1\). So \(\ket0\ket\phi\mapsto\ket0\ket\phi\) and \(\ket1\ket\phi\mapsto-\ket1\ket\phi\), which is \(Z\) on the control. Uncontrolled, \(-I\) does nothing observable; controlled, it is a \(Z\) gate.
The rotation \(R_z(\theta)=\mathrm{diag}(e^{-i\theta/2},e^{i\theta/2})\) and the phase gate \(P(\theta)=\mathrm{diag}(1,e^{i\theta})\) differ by a global phase. What is the relative phase on the control between their controlled versions?
Show solutionHide solution
\(P(\theta)=e^{i\theta/2}R_z(\theta)\). So \(\mathrm{C}P(\theta)=\mathrm{C}R_z(\theta)\cdot(P(\theta/2)\otimes I)\): the controlled versions differ by a phase gate \(P(\theta/2)\) on the control.
In phase estimation, \(U\) has eigenvalue \(e^{2\pi i\phi}\) on \(\ket u\). If a compiler silently replaces \(U\) by \(e^{i\alpha}U\) before controlling it, what does phase estimation report?
Show solutionHide solution
The eigenvalue becomes \(e^{i(2\pi\phi+\alpha)}\), so it reports \(\phi+\alpha/2\pi\) (mod 1). Every eigenphase shifts by the same amount. Differences between eigenphases are unaffected, but absolute phases, such as energies in a simulation, are wrong.
What does a clean oracle actually hand to its caller? Applied to a superposition it produces \(\sum_x\alpha_x\ket{x}\ket{f(x)}\). It is tempting to say this “computes all values of \(f\).” It does not, in any sense a user can collect. Measuring yields one pair \((x,f(x))\) with probability \(|\alpha_x|^2\). Collecting all \(2^n\) values by repetition would take at least \(2^n\) runs, more than a classical program that simply evaluates each.
A state of this kind is useful only if the next coherent operation extracts a property from it: a phase pattern resolved by Hadamards, a period resolved by a Fourier transform, or a marked component amplified by reflections. The subroutine’s contract should therefore say what form its output takes and what the caller is expected to do with it.
A subroutine’s contract should state which output form it delivers. Converting a state into classical data costs repetitions that grow with the amount of data and the precision required.
We now have a concrete method for evaluating functions coherently, the costs it incurs, and the access a subroutine can offer: forward, inverse, controlled, and the reflection built from them. When the retained effect is a sign, the computation has become a phase encoding, and that encoding is what we learn to read next.
Problems
For \(n=10\) and the uniform superposition, how many runs of “evaluate and measure” are needed on average to see every input at least once?
Show solutionHide solution
This is the coupon-collector problem: on average \(N(1+\frac12+\cdots+\frac1N)\approx N\ln N\) runs for \(N=1024\), about \(1024\times7.5\approx7700\). A classical program needs exactly 1024 evaluations.
A subroutine’s output is “the state \(\sum_x\alpha_x\ket x\ket{f(x)}\) with a clean workspace.” Name two different follow-up operations from later chapters and the classical output each produces.
Show solutionHide solution
(i) Uncompute and use the phase variant, then apply Hadamards and measure: Bernstein–Vazirani returns a hidden string \(s\) when \(f(x)=s\cdot x\). (ii) Measure the function register, then apply a Fourier transform to the input and measure: period finding returns a sample related to the period of \(f\). Each produces a short classical answer about a global property of \(f\), not the table of values.
Why must a subroutine whose output is a quantum state specify its accuracy as a distance between states, rather than as an error in each amplitude?
Show solutionHide solution
Small errors in each of \(2^n\) amplitudes can add up to a large total error, and errors in amplitudes that are tiny can be irrelevant. What matters for every later use is how different the measurement statistics can be, which is bounded by a state distance such as \(\|\ket\psi-\ket{\tilde\psi}\|\). For normalized states, a distance \(\|\ket\psi-\ket{\tilde\psi}\|\le\epsilon\) bounds the change in every outcome probability, for every measurement, by at most \(\epsilon\).
Summary
Any classical circuit can be made reversible using Toffoli gates and clean ancilla qubits so that \(|x,0,0\rangle \mapsto |x,w(x),f(x)\rangle\) preserves quantum coherence across superpositions.
Leftover workspace bits \(w(x)\) entangle with the input register and destroy interference unless they are uncomputed via Bennett’s compute–copy–uncompute trick.
Trading ancilla width against circuit depth changes the physical footprint of a subroutine without changing its logical action on the input and output registers.
Questions and worked problems
Attempt each question before opening a hint. Explain your reasoning, then compare it with the solution.
A circuit maps |x⟩|0⟩|0⟩ to |x⟩|f(x)⟩|x₁⟩, where x₁ is the first bit of x. Does it satisfy the clean contract? What would it do to the Deutsch–Jozsa experiment for inputs that differ in x₁?
Hint 1
The contract requires the workspace to return to |0⟩ on every input.
Hint 2
A workspace bit that depends on x is a which-path record.
Worked solution
No: the workspace holds x₁, which depends on the input. In the Deutsch–Jozsa experiment, branches with different x₁ carry orthogonal workspace states and cannot interfere, so the final Hadamards no longer concentrate amplitude on the answer. Uncomputing x₁ (a CNOT from x₁ into the workspace) repairs it.
A circuit maps \(\ket x\ket0\ket0\mapsto\ket x\ket{f(x)}\ket{f(x)}\): it leaves a second copy of the answer in its one workspace qubit. Since the garbage is “only the answer,” is the oracle clean? Use it with the output target in \(\ket-\) inside Deutsch’s algorithm and find the probability of the correct answer for a balanced \(f\).
Hint 1
The contract requires the workspace to return to \(\ket0\) on every input.
Hint 2
After the query the two input branches carry workspace values \(f(0)\neq f(1)\).
Worked solution
No. The clean contract requires the workspace to return to \(\ket{0}\); here it holds \(f(x)\), which depends on the input. With the target in \(\ket-\), the query gives \(\frac{1}{\sqrt2}\big((-1)^{f(0)}\ket0\ket{f(0)}+(-1)^{f(1)}\ket1\ket{f(1)}\big)\ket-\). For a balanced function the workspace values differ, so the workspace is a which-path record. After the final Hadamard the input outcomes \(0\) and \(1\) each have probability \(1/2\), so the answer is correct only half the time. For a constant function the workspace is the same on both branches and the circuit still works, which is why a test on constant inputs alone would not reveal the bug.
A clean oracle for a predicate with exactly one marked input among \(N=2^{10}\) is applied to the uniform superposition with target \(\ket0\), and the target is measured. What is the probability of seeing \(1\)? If it is seen, what is the state of the input register, and why is this not yet a fast search algorithm?
Hint 1
The state is \(2^{-5}\sum_x\ket x\ket{f(x)}\).
Hint 2
How many repetitions are expected before the target reads \(1\)?
Worked solution
The marked branch has amplitude \(2^{-5}\), so the target reads \(1\) with probability \(1/1024\). When it does, the input collapses to the marked string \(\ket{x^*}\), which can be read out. But a success probability of \(1/N\) means about \(N\) repetitions on average, the same as testing inputs one by one. The clean oracle has written the answer into the state without making it likely to be observed. Increasing the marked amplitude before measuring is the job of amplitude amplification in the Amplitude Manipulation chapter, which needs the reflections built from clean preparation and inverse access.
Build a clean phase oracle for f(a,b,c) = a AND b AND c using one ancilla, and count Toffolis.
Hint 1
Compute g = a AND b into the ancilla with a Toffoli.
Hint 2
A controlled-Z between g and c applies (−1)^{abc}.
Worked solution
Toffoli from a,b into g; controlled-Z between g and c (phase −1 exactly when g = c = 1, i.e. a = b = c = 1); Toffoli from a,b into g again to uncompute. Two Toffolis and one CZ, with the ancilla returned to |0⟩. Equivalently, a doubly controlled Z on a,b,c decomposed with one ancilla.
The majority function on three bits is \(\mathrm{MAJ}(a,b,c)=ab\oplus ac\oplus bc\). (a) Check this identity on all inputs with at least two ones. (b) Build a clean oracle \(\ket{abc}\ket y\mapsto\ket{abc}\ket{y\oplus\mathrm{MAJ}}\) with no workspace and count Toffolis. (c) Build the phase oracle \((-1)^{\mathrm{MAJ}}\) with no Toffolis at all.
Hint 1
Each product term can be added directly into the target.
Hint 2
\((-1)^{u\oplus v\oplus w}=(-1)^u(-1)^v(-1)^w\), and a controlled-\(Z\) applies \((-1)^{ab}\).
Worked solution
(a) If exactly two bits are \(1\), exactly one product is \(1\), so the XOR is \(1\). If all three are \(1\), all three products are \(1\) and \(1\oplus1\oplus1=1\). With fewer than two ones every product is \(0\). (b) Apply three Toffolis into \(y\), controlled on \((a,b)\), \((a,c)\), and \((b,c)\). Each adds one term by XOR, so \(y\) receives \(\mathrm{MAJ}\). No intermediate value is stored, so there is nothing to uncompute: three Toffolis and no ancilla, compared with three Toffolis, three ancillas, and an uncompute for a naive translation. (c) The phase factorizes as \((-1)^{ab}(-1)^{ac}(-1)^{bc}\), so three controlled-\(Z\) gates on the three pairs implement the phase oracle exactly. The lesson: when a function is an XOR of terms, computing each term straight into the target, or straight into a phase, avoids garbage altogether.
Let \(\mathrm{INC}\) be the two-bit incrementer, \(\ket j\mapsto\ket{j+1\bmod4}\), with \(j=2b_1+b_0\). Apply it to \(\ket{\chi}=\frac12(\ket0-\ket1+\ket2-\ket3)\) and to \(\ket{\eta}=\frac12(\ket0+i\ket1-\ket2-i\ket3)\). What do you find? Generalize to amplitudes \(c_j=i^{jk}/2\).
Hint 1
If the input amplitudes are \(c_j\), the output amplitude on \(\ket j\) is \(c_{j-1}\).
Hint 2
Compare \(c_{j-1}\) with \(c_j\).
Worked solution
Since \(\mathrm{INC}\sum_jc_j\ket j=\sum_jc_{j-1}\ket j\) (indices mod 4), each output amplitude is the input amplitude of the previous label. For \(\ket\chi\), \(c_j=(-1)^j/2\) and \(c_{j-1}=-c_j\), so \(\mathrm{INC}\ket\chi=-\ket\chi\). For \(\ket\eta\), \(c_j=i^j/2\) and \(c_{j-1}=i^{-1}c_j\), so \(\mathrm{INC}\ket\eta=-i\ket\eta\). In general \(c_j=i^{jk}/2\) gives \(c_{j-1}=i^{-k}c_j\): the state is unchanged except for the factor \(e^{-2\pi ik/4}\). These four states, one for each \(k\), are the eigenstates of modular addition; the arithmetic shows up only as a phase. The Fourier Methods chapter exploits exactly this: controlled powers of modular arithmetic, applied to such states, write \(k/4\) into a phase that the Fourier transform can read.
A computation has \(k=8\) stages \(u_i=F_i(u_{i-1})\), \(u_0=x\). Compare two reversible schedules that end holding only \(x\) and \(u_8\). (a) Keep everything: compute all stages, copy \(u_8\), uncompute the rest. (b) Recursive halving: to reach stage \(k\), pebble stage \(k/2\), use it to pebble stage \(k\), then unpebble stage \(k/2\). Count stage evaluations and the maximum number of stage values held at once in each.
Hint 1
For (b), the cost satisfies \(P(k)=3P(k/2)\) with \(P(1)=1\).
Hint 2
The peak memory satisfies \(S(k)=S(k/2)+1\) with \(S(1)=1\).
Worked solution
(a) Computing \(u_1,\dots,u_8\) takes \(8\) evaluations and uncomputing \(u_7,\dots,u_1\) takes \(7\), so \(15\) evaluations with up to \(8\) stage values held. (b) Reaching stage \(k\) costs three half-size problems, so \(P(8)=3P(4)=9P(2)=27P(1)=27\) evaluations. While the second half runs, \(u_{k/2}\) must be kept in addition to that half’s own peak, so \(S(8)=S(4)+1=S(2)+2=S(1)+3=4\). Recursion halves the memory at the cost of almost doubling the work. In general it uses about \(k^{\log_23}\approx k^{1.58}\) evaluations and \(\log_2k+1\) stored values. On a quantum computer, where each stored value occupies qubits that must stay coherent, trading evaluations for qubits is often worthwhile.
Circuit \(C\) computes \(g=ab\) into a workspace qubit (Toffoli), then \(t=g\oplus c\). A programmer uncomputes with a different circuit \(C'\) for the same \(f=ab\oplus c\): \(C'\) copies \(a\) into the workspace (CNOT), applies a Toffoli from the workspace and \(b\) into \(t\), then a CNOT from \(c\) into \(t\). They apply \(C\), copy \(t\) into \(y\), then \(C'^{-1}\). “Both circuits compute \(f\), so either can uncompute.” Trace a basis input and find what remains in the workspace.
Hint 1
\(C'^{-1}\) applies the gates of \(C'\) in reverse order.
Hint 2
After \(C\), the workspace holds \(ab\), not \(a\).
Worked solution
After \(C\) and the copy, the registers hold \((a,b,c,\;w=ab,\;t=ab\oplus c,\;y\oplus f)\). Now \(C'^{-1}\): the CNOT from \(c\) gives \(t=ab\); the Toffoli from \(w=ab\) and \(b\) adds \(ab\cdot b=ab\), so \(t=0\); the CNOT from \(a\) gives \(w=ab\oplus a=a\land\lnot b\). The target is cleared by coincidence, but the workspace holds \(a\land\lnot b\), which is \(1\) on inputs with \(a=1,b=0\). The oracle is dirty and will destroy interference between those inputs and the rest. The principle: an uncomputation must undo the particular intermediate values the computation produced. Using the exact reverse of \(C\) guarantees this; another circuit for \(f\) generally assumes different garbage.
A preparation circuit A uses 500 gates. Each amplification iteration in the Amplitude Manipulation chapter uses one reflection about the prepared state and one phase oracle costing 300 gates. Estimate the gate cost of 20 iterations, including an initial preparation, and identify which access assumptions the count relies on.
Hint 1
The reflection about the prepared state uses A, A†, and a zero-state reflection.
Hint 2
The zero-state reflection on n qubits costs O(n) Toffolis; call it z gates.
Worked solution
Each iteration costs 300 (oracle) + 500 (A†) + z (zero reflection) + 500 (A) = 1300 + z gates. Twenty iterations plus the initial A cost 500 + 20(1300 + z) = 26,500 + 20z gates. The count assumes a known gate sequence for A, so that A† is available at equal cost, and a clean oracle; with only a sealed box for A, the reflection could not be built this way.
Suppose uncomputation is imperfect, so the two input branches of the garbage-interference test carry workspace states \(\ket{g_0}\) and \(\ket{g_1}\) instead of identical ones. After the CNOT the state is \(\frac{1}{\sqrt2}(\ket{000}\ket{g_0}-\ket{100}\ket{g_1})\). Show that the Hadamard on the first bit gives outcome \(1\) with probability \(\frac12(1+\mathrm{Re}\braket{g_0}{g_1})\). Evaluate it for \(\ket{g_0}=\ket0,\ket{g_1}=\ket+\), and interpret the clean and fully dirty cases.
Hint 1
Collect the terms with first bit \(0\): their vector is \(\frac12\ket{00}(\ket{g_0}-\ket{g_1})\).
After the Hadamard the state is \(\frac12\big[\ket0\ket{00}(\ket{g_0}-\ket{g_1})+\ket1\ket{00}(\ket{g_0}+\ket{g_1})\big]\). The probability of first bit \(1\) is \(\frac14\|\ket{g_0}+\ket{g_1}\|^2=\frac14(2+2\,\mathrm{Re}\braket{g_0}{g_1})=\frac12(1+\mathrm{Re}\braket{g_0}{g_1})\). Clean (\(\ket{g_0}=\ket{g_1}\)): probability \(1\). Fully dirty, orthogonal garbage (as with \(\ket{00}\) versus \(\ket{11}\)): probability \(1/2\), a fair coin. For \(\ket0\) and \(\ket+\), the overlap is \(1/\sqrt2\) and the probability is \(\frac12(1+1/\sqrt2)\approx0.854\). Interference visibility is set by the overlap of the leftover records: partial garbage gives partial damage, and the error compounds when the oracle is called many times.
Where this leads. the Phase Encoding chapter uses clean phase oracles to encode a hidden linear function in signs and recovers it in one query with a layer of Hadamards, then extends the idea to hidden structure and numerical phases.