DiracDirac

Part II · Algorithms and What They Really Buy · Chapter 6

Interference as Computation

A classical computer asks a question and reads one answer. A quantum computer can ask about every input at once — then arrange for the wrong answers to cancel, leaving the right one standing. This chapter is where amplitudes first do something a probability cannot.

Sources: Nielsen & Chuang 1.4, 6 · Mathematics of Quantum Computing

Part I built the machine; now we run it. The first algorithms of quantum computing are almost toys — they solve artificial problems about black-box functions — but they are the cleanest place to watch the one trick that everything else refines: interference. An amplitude can be negative, and negatives can cancel. Put a function into superposition, let the oracle stamp its answers as signs, and interfere the branches so that a single measurement reveals a global property no single evaluation could. We will be scrupulously honest about the ledger: these are query-complexity speedups on promise problems, not a proof that quantum beats classical in general. But the mechanism is the real thing, and it is the seed of Shor.

What this chapter covers

  • 6.1The query model. An unknown function as a black-box unitary U_f; query complexity as the honest unit of cost.
  • 6.2Phase kickback. Set the target to |−⟩ and the XOR oracle becomes a pure sign (−1)^{f(x)} on the input — the central trick.
  • 6.3Deutsch–Jozsa. One query decides constant vs balanced, where a deterministic classical machine may need 2ⁿ⁻¹+1 — plus who actually gets the credit for the one-query, always-correct form.
  • 6.4Bernstein–Vazirani. Recover a hidden n-bit string s from f(x)=s·x in a single query — the same circuit, read differently.
  • 6.5What it really buys. The honest scorecard: query vs time complexity, promise problems, and why this is not yet BQP ⊋ P.
  • 6.6The Lab. A fresh oracle simulator with Deutsch–Jozsa and Bernstein–Vazirani, refereed to machine precision — and the classical lower bound proven by brute-force enumeration, not quoted.

6.1The query model

F · Formalism

Suppose someone hands you a function as a sealed box: you may feed it inputs and read outputs, but you cannot look at its wiring. How many times must you use the box to learn some property of ? That count — the number of queries — is the cost we track in this chapter, and it is a genuinely different accounting from counting gates or seconds. It isolates one question: how much can be learned per evaluation of the unknown function?

A quantum computer cannot use a classical box; every operation between preparation and measurement must be unitary and reversible (Chapter 2). So the oracle is given to us as a reversible unitary on qubits — an -bit input register and a one-qubit target (or ancilla) — that writes the answer by XOR:

(6.1)

XOR-ing rather than overwriting is what keeps invertible: apply it twice and the target returns to , so and is its own inverse — manifestly unitary, a permutation of the computational basis. Feed the input register a superposition and, by linearity, one use of the box touches every value of at once:

(6.2)

This looks like magic and is not: the result is entangled, and reading it gives just one random pair, no better than one classical query (the Holevo ceiling of Chapter 1 is still in force). The superposition alone buys nothing. What we need is a way to make the branches interfere before we look — and for that we need the branches to carry signs, not just labels. That is the next section.

6.2Phase kickback

F · Formalism

Here is the pivot the whole chapter turns on. Prepare the target not in but in , the state that flips by a sign: . Since applies to the target exactly when , watch what happens on a basis input :

(6.3)

The target comes out unchanged — still — but its eigenvalue has been kicked back onto the input register as a phase. The oracle, which physically writes bits, now acts on the inputs as the pure phase oracle

(6.4)

with the target left as an untouched spectator. This is not an approximation or a convention — it is an exact operator identity, and it is the first referee in the lab, checked to be exactly zero — the referee's tolerance is 0.0, not merely small — against an independent implementation of . Both sides of it are drawn in Figure 6.1.

phase kickback — the oracle’s bit becomes the input’s signA · the honest XOR oracle, one query|x⟩|−⟩Uf(−1)f(x)|x⟩|−⟩ untouchedthe target is a spectator=B · the phase oracle it becomes, no ancilla|x⟩Df± |x⟩+000100010+110001+101+011111the signs for f(x) = x₀⊕x₁⊕x₂ — four +, four −their average is 0: that cancellation is the computationU_f |x⟩|−⟩ = (−1)^f(x) |x⟩|−⟩ — a written bit read back as a phase
Figure 6.1. Phase kickback, both sides of the identity (6.3). Left: the honest XOR oracle U_f, one query, acting on an input |x⟩ and a target prepared in |−⟩ — the target comes out untouched while the input carries away the sign (−1)^f(x). Right: the object that leaves behind, the ancilla-free phase oracle D_f = diag((−1)^f(x)), and the eight signs it stamps on a three-bit register for the balanced example f(x) = x₀⊕x₁⊕x₂ — four plus, four minus, so their average is zero. Qubit 0 is written leftmost in every label, the book's convention.

Now the branches carry signs. Run on the uniform superposition and the amplitudes are ; a final Hadamard layer turns those signs into constructive and destructive interference. Toggle a function below and watch the signs appear and then interfere to a verdict:

Pick a function f

Toggle each output f(x). The oracle turns every 1 into a minus sign on that branch — the phase kickback — and the final Hadamards interfere them.

verdict:balanced(2 ones of 4)

Amplitude on |00⟩ is a₀ = 0.000: exactly 0, so all-zeros is impossible ⇒ balanced.

phases (−1)^f(x) on the input register++output probabilities after the final H layer001.00100111

Notice the pattern the explorer makes plain. The amplitude that lands back on is the average of the signs, : it is when the signs all agree (a constant ) and exactly when they split evenly (a balanced ), because the plus and minus halves cancel term for term. That cancellation is the computation.

6.3Deutsch–Jozsa

C · ConceptsF · Formalism

The observation of §6.2 is an algorithm. You are promised that is either constant (the same value on all inputs) or balanced (value 0 on exactly half the inputs, 1 on the other half). Which is it? The Deutsch–Jozsa circuit — in the deterministic one-query form built here, which is the 1998 refinement by Cleve, Ekert, Macchiavello and Mosca rather than either original — answers in a single query: put the ancilla in , Hadamard every input qubit into the uniform superposition, query once, Hadamard the inputs again, and measure them.

the Deutsch–Jozsa circuit — one query decidestime flows left → rightq₀: |0⟩q₁: |0⟩qₙ₋₁: |0⟩anc: |0⟩n inputsXH|−⟩HHHUf|x⟩|y⟩→|x⟩|y⊕f(x)⟩HHH|−⟩ (discarded)all zeros ⇒ f is constant · any other outcome ⇒ f is balanced
Figure 6.2. The Deutsch–Jozsa circuit. The ancilla is prepared in |−⟩ so the single oracle query acts as the phase D_f. The Hadamard layers convert the uniform superposition into ±1 amplitudes and then interfere them: the input register reads all-zeros with certainty if f is constant, and never reads all-zeros if f is balanced. Qubit 0 is the top wire; 'leftmost' refers to its place in the ket label |q₀q₁…⟩, the book's convention.

The measured amplitude of outcome works out to

(6.5)

the Hadamard transform of the sign pattern. For this is the average of §6.2: a constant gives , so occurs with probability exactly 1; a balanced gives , so that outcome is impossible. One query, one bit of measurement, a certain answer. The lab confirms both determinisms over hundreds of random oracles across a range of register sizes (the panel in §6.6 reports the sweep it ran): the constant case lands on all-zeros with probability 1 to within its referee's tolerance of , and the balanced case lands there with probability below — the residue of a cancellation between amplitudes of equal magnitude, and so quadratically smaller.

David Deutsch found the case in 1985: a single-bit is constant () or balanced (), and he showed that a single quantum query can settle it where a classical machine plainly needs both evaluations — but only half the time. Deutsch's 1985 algorithm succeeds with probability and otherwise reports failure rather than a wrong answer, so you know to run it again: one query when it works, two on average. Deutsch and Jozsa generalized the problem to bits in 1992 and made the answer certain, at the price of two queries; the deterministic single-query circuit of Figure 6.2 — the one we build and referee here — is the 1998 refinement by Cleve, Ekert, Macchiavello and Mosca. The gap it exposes is dramatic: a deterministic classical algorithm must, in the worst case, check inputs before it can be sure — one more than half, since half-plus-one identical answers is the first count a balanced function cannot fake. The quantum machine needs one.

The very same circuit, pointed at a different promise, does something that feels even more like getting information for free. Suppose is the dot product with a hidden string ,

(6.6)

Classically, each query reveals one bit about : query the unit strings and read off one at a time — queries for bits, and you cannot do better. Run Deutsch–Jozsa instead. After the kickback the input register is

(6.7)

because is precisely the sign pattern the Hadamard transform puts on . A second Hadamard layer is again, and , so the register collapses to exactly : measuring hands you the whole hidden string, all bits, from a single query. The lab runs this over hundreds of random hidden strings , at every register size up to the largest the panel in §6.6 reports, and recovers exactly — probability 1, every trial, no exceptions.

It is worth pausing on why this is not a paradox. The single query still obeys Holevo — you measure once and get bits out of an -qubit register, which is allowed. What was beaten is the classical query count, and only because the quantum query, via kickback, extracts a global parity of rather than a single value. The oracle was always willing to tell you in one shot; the classical interface just could not ask the right question.

Time for the honest ledger, because the folklore here is bad. Three caveats turn “exponential speedup” into something precise and much narrower.

It is query complexity, not time. We counted calls to the black box. That is a real and provable resource — the Deutsch–Jozsa gap of versus is a theorem, not a conjecture — but it says nothing directly about wall-clock time on ordinary inputs, where the function is a circuit you can inspect, not a sealed box.

They are promise problems. Deutsch–Jozsa only works because you are promised is constant or balanced; feed it a function that is neither and the verdict is meaningless (the explorer in §6.2 shows this directly). Real inputs rarely come with such promises.

The deterministic gap partly evaporates under randomness. A classical algorithm allowed to guess can solve Deutsch–Jozsa with a handful of random queries and tiny error probability: sample a few inputs, and a balanced function almost certainly shows both values. The clean is a deterministic, exact worst case. Bernstein–Vazirani is sturdier — it beats randomized classical query complexity too — but even there the separation is polynomial ( versus ), not exponential.

So what is genuinely bought? A mechanism. These algorithms are the first proof that arranging amplitudes to interfere lets a single measurement report a global property of a function that no single evaluation reveals. That is not yet a proof that — nobody has one — but it is the exact device that, aimed at periodicity instead of parity, becomes Shor's factoring algorithm in Chapter 7, where the speedup is over the best known classical time, on a problem the world's cryptography depends on. Toys first, then the real thing.

The lab builds a fresh state-vector simulator (the Chapter 2 engine in miniature) and adds the one new object of this chapter: the oracle. The honest XOR oracle is a permutation of amplitudes; the phase oracle it becomes under kickback is a sign flip. Two independent implementations — which the first referee then forces to agree:

ch06-oracles/src/main.rs — the two oracles
1impl State {
2 // …
3
4 /// The honest XOR oracle U_f: |x>|y> -> |x>|y XOR f(x)>, input in bits
5 /// 0..n_in, ancilla in bit n_in. Implemented as the permutation it is —
6 /// swap the ancilla-0 and ancilla-1 amplitudes of every x with f(x)=1. This
7 /// is a genuine unitary; no phases are put in by hand.
8 fn apply_xor_oracle(&mut self, f: &[u8], n_in: usize) {
9 let anc = 1usize << n_in;
10 for x in 0..(1usize << n_in) {
11 if f[x] == 1 {
12 self.amps.swap(x, x | anc);
13 }
14 }
15 }
16
17 /// The phase oracle D = diag((-1)^{f(x)}) on n_in qubits — the object phase
18 /// kickback is supposed to produce. An INDEPENDENT code path (no ancilla, no
19 /// XOR, just a sign flip) used only to referee the kickback identity.
20 fn apply_phase_oracle(&mut self, f: &[u8]) {
21 for x in 0..self.dim() {
22 if f[x] == 1 {
23 self.amps[x] = -self.amps[x];
24 }
25 }
26 }
27}

The phase-kickback referee builds for random , applies the honest one way and the phase oracle the other, and demands they match — the identity (6.3) verified, not assumed:

ch06-oracles/src/main.rs — the phase-kickback referee
1fn main() -> Result<(), Box<dyn Error>> {
2 // …
3
4 // --- Referee 1: phase kickback identity -------------------------------
5 // For random input states |psi> and random oracles f, the honest XOR oracle
6 // acting on |psi>|-> equals the phase oracle diag((-1)^{f(x)}) acting on
7 // |psi>, tensored with an untouched |->. Two independent code paths.
8 let inv_sqrt2 = 1.0 / 2.0_f64.sqrt();
9 let mut worst_kick: f64 = 0.0;
10 for _ in 0..400 {
11 let n_in = rng.gen_range(1..=6);
12 let dim = 1usize << n_in;
13 // random input amplitudes (normalization is irrelevant to a linear id.)
14 let psi: Vec<C> = (0..dim)
15 .map(|_| c(rng.gen::<f64>() * 2.0 - 1.0, rng.gen::<f64>() * 2.0 - 1.0))
16 .collect();
17 let f: Vec<u8> = (0..dim).map(|_| rng.gen_range(0..2u8)).collect();
18
19 // Path A: build |psi>|-> explicitly, apply the honest permutation U_f.
20 let anc = 1usize << n_in;
21 let mut full = State { n: n_in + 1, amps: vec![c(0.0, 0.0); dim * 2] };
22 for x in 0..dim {
23 full.amps[x] = psi[x] * inv_sqrt2; // ancilla |0> branch
24 full.amps[x | anc] = -psi[x] * inv_sqrt2; // ancilla |1> branch of |->
25 }
26 full.apply_xor_oracle(&f, n_in);
27
28 // Path B: apply the phase oracle to |psi> directly, tensor with |->.
29 let mut inp = State { n: n_in, amps: psi.clone() };
30 inp.apply_phase_oracle(&f);
31 let mut expect = vec![c(0.0, 0.0); dim * 2];
32 for x in 0..dim {
33 expect[x] = inp.amps[x] * inv_sqrt2;
34 expect[x | anc] = -inp.amps[x] * inv_sqrt2;
35 }
36
37 for i in 0..dim * 2 {
38 worst_kick = worst_kick.max((full.amps[i] - expect[i]).norm());
39 }
40 }
41 assert!(worst_kick.is_finite()); // FINITE before small
42 // …
43}

Deutsch–Jozsa is then just the circuit of Figure 6.2, read off as the all-zeros probability. Bernstein–Vazirani reuses it verbatim, only reading the recovered string instead of a yes/no:

ch06-oracles/src/main.rs — the Deutsch–Jozsa circuit
1/// The Deutsch–Jozsa circuit on n_in input qubits + 1 ancilla. Returns the
2/// probability that measuring the whole input register yields |0...0>.
3/// ancilla: X then H (-> |->) inputs: H on each (-> uniform)
4/// one query U_f inputs: H on each measure inputs
5fn dj_all_zero_prob(f: &[u8], n_in: usize) -> f64 {
6 let n_total = n_in + 1;
7 let mut s = State::basis(n_total, 0);
8 s.apply_1q(&g_x(), n_in); // ancilla |0> -> |1>
9 s.apply_1q(&g_h(), n_in); // -> |->
10 for q in 0..n_in {
11 s.apply_1q(&g_h(), q);
12 }
13 s.apply_xor_oracle(f, n_in);
14 for q in 0..n_in {
15 s.apply_1q(&g_h(), q);
16 }
17 // Input register = all zeros means the input bits are 0; the ancilla can be
18 // either value, so sum the two amplitudes at index 0 and index (ancilla=1).
19 let anc = 1usize << n_in;
20 s.amps[0].norm_sqr() + s.amps[anc].norm_sqr()
21}

The referees — four independent physics checks, with Deutsch–Jozsa and Bernstein–Vazirani each refereeing two quantities — run and write their results to JSON, which the panel below reads live, names, values and tolerances alike; nothing here is hardcoded. Phase kickback holds exactly (tolerance 0.0, because the two code paths do no arithmetic that could round differently); Deutsch–Jozsa is deterministic to (constant) and (balanced); Bernstein–Vazirani recovers exactly in every trial; and the classical bound is proven by brute force at the small sizes the panel names. The proof enumerates all balanced truth tables once, then for every one of the possible query sets of size it searches that list for a balanced function consistent with all-zero answers on the set. One always exists, so a constant and a balanced verdict both survive and no deterministic strategy, however clever or adaptive, can decide in queries. The other direction is read off the same enumeration: no balanced function can hide past query , and the worst one hides for exactly — so the bound is tight, not merely respected. Every function in the enumeration is then decided by the simulator in a single query. For larger the formula is quoted, not proven:

Loading /data/ch06/oracles.json… (run cargo run --release in Rust-QML/ch06-oracles)

Run it yourself with cargo run --release in Rust-QML/ch06-oracles. The simulator ends with ALL REFEREES PASSED. Keep the phase-kickback trick in view: Chapter 7 points the same interference at the structure of periodic functions, and that is where the toys turn into Shor.

6.7Exercises

1. (F) Verify the kickback identity (6.3) by hand for both target inputs: compute and , take the combination, and confirm the falls out. Why does on the target not produce a useful phase?

2. (F) Derive the output amplitude (6.5) from scratch: apply to the uniform state, then , then again, using . Confirm is the average of the signs.

3. (C) In the kickback explorer at , find a function whose verdict is “neither” and read off its . Explain in one sentence why the Deutsch–Jozsa answer is then not to be trusted, connecting it to the word promise in §6.5.

4. (P) Add a Deutsch () routine to the lab that returns the single bit “constant?” and verify it on all four one-bit functions. Then add a classical deterministic solver and confirm it needs two queries where the quantum one needs a single query.

5. (P, hard) Implement Simon's problem: an oracle with a hidden such that . Show that one quantum query yields a random with , and that queries recover by solving a linear system over — the first exponential separation against randomized classical query complexity, and the direct ancestor of Shor. Referee it by checking the recovered against the planted one over many random instances.

The bridgeChapter 7: The Fourier Family

Where you stand. You have the query model, phase kickback, and the two algorithms it powers — Deutsch–Jozsa (constant vs balanced in one query) and Bernstein–Vazirani (a hidden string in one query) — plus an honest accounting of what a query speedup is and is not, all refereed to machine precision on a fresh oracle simulator.

The open question. Deutsch–Jozsa reads a global parity of f by interfering signs; Bernstein–Vazirani reads a whole hidden string the same way. Both are the Hadamard transform in disguise. What if the global structure we want is not a parity but a period — the spacing of a repeating function? What transform interferes THAT into a single measurement?

What comes next. We build the quantum Fourier transform: the n-qubit generalization of the Hadamard that turns periodicity into a measurable phase. With it comes phase estimation, and then order-finding — the engine of Shor's algorithm, the first quantum speedup over the best known classical TIME, on a problem (factoring) that the world's cryptography assumes is hard.

Continue to Chapter 7