Deutsch-Jozsa: The First Quantum Speedup
The Deutsch-Jozsa algorithm separates constant from balanced Boolean functions in a single query, where classical deterministic algorithms need up to 2ⁿ⁻¹ + 1. This tutorial derives the algorithm from first principles, explains phase kickback, and walks through the full Qiskit implementation plus the Deutsch n=1 special case.
Prerequisites: Gates & Circuits track (Tutorials 4-7)
Deutsch-Jozsa is the Hello World of quantum algorithms — and also the first formal proof that quantum computers can do things classical ones fundamentally can’t. It’s not a useful algorithm in any practical sense (the problem it solves doesn’t exist in the wild) but the ideas it introduces — oracles, phase kickback, interference at the output — are the scaffolding of every subsequent algorithm you’ll learn.
If you understand Deutsch-Jozsa deeply, you can understand Grover, Shor, and quantum phase estimation. If you don’t, you’ll be memorizing gate sequences forever.
The problem
You’re given a Boolean function as a black box — you can query it, but you can’t peek at its code. You’re promised that is one of two kinds:
- Constant: for all , or for all .
- Balanced: outputs on exactly half its inputs and on the other half.
Your job: decide which, with as few queries as possible.
Classical bound. With a deterministic classical algorithm, the worst case requires queries. Here’s why: if you see queries that all returned , the function could still be balanced (all the remaining inputs might return ) or constant. Only on query are you forced to see either a (balanced) or a -th (constant, since a balanced function can’t have more than zeros).
Quantum bound. A quantum algorithm solves this with a single query. One. That’s the Deutsch-Jozsa algorithm.
The speedup is exponential in the worst case ( vs 1), though it vanishes under a randomized classical algorithm (any balanced-vs-constant test reaches arbitrarily small error with random samples). Deutsch-Jozsa is primarily a proof of worst-case deterministic separation between classical and quantum.
The oracle
To feed into a quantum circuit, you need a reversible version. Classical is generally not reversible (many-to-one). The standard fix: a unitary acting on qubits that XOR’s the output into a dedicated target qubit:
This is reversible because applying twice returns to the original state. It’s a formalism every oracle-based quantum algorithm inherits.
Phase kickback: the trick that makes it work
Here is the one idea you need to internalize. Put the target qubit into the state and watch what happens when acts:
If , the target is (unchanged). If , it’s (negated). Rearrange:
The oracle’s output has been moved from the target qubit into the phase of the input qubit. The target qubit is unchanged; the input qubit picks up a phase factor depending on .
This is phase kickback. It converts an oracle “that computes ” into one “that marks inputs with by a negative sign” — and that phase pattern is what quantum interference can read.
The Deutsch-Jozsa circuit
Now build the algorithm:
- Prepare input qubits in and one ancilla in .
- Apply to every qubit. Inputs become uniform superposition; ancilla becomes .
- Apply the oracle . Phase kickback gives:
- Apply to the inputs. This is the quantum Fourier transform over — it decomposes the sign pattern into its Hadamard components. The result:
- Measure the inputs in the computational basis.
The punchline
Look at the amplitude of (i.e., ) in :
- Constant : every term is , sum is , . Measurement gives with certainty.
- Constant : every term is , (the negative global phase is unobservable). Still .
- Balanced : half the terms are and half are , sum is . . can never appear.
So you measure once. If you get , is constant. If you get anything else, is balanced. One query. Done.
Deutsch n=1 in OpenQASM
The special case (Deutsch’s original 1985 algorithm) has four possible functions:
| Kind | Oracle | |
|---|---|---|
| Constant | Identity on ancilla | |
| Constant | X on ancilla | |
| Balanced | CNOT, control = input | |
| Balanced | CNOT then X on ancilla |
Pick the balanced oracle. Circuit:
OPENQASM 2.0;
include "qelib1.inc";
qreg q[2]; // q[0] = input, q[1] = ancilla
creg c[1];
// Prep: |0⟩|1⟩ then H on both → |+⟩|−⟩
x q[1];
h q[0];
h q[1];
// Oracle for f(x) = x: CNOT from input to ancilla
cx q[0], q[1];
// Final H on input
h q[0];
measure q[0] -> c[0];
Run it: you’ll see 1 on every shot. Swap the cx for nothing (constant ) or x q[1] (constant ), and you’ll see 0 every shot.
→ Open this circuit in the playground (pick “Deutsch-Jozsa” from the examples dropdown, or paste the QASM above).
General in Qiskit
Here’s a clean implementation that takes a user-supplied oracle and runs the algorithm:
from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator
def deutsch_jozsa_circuit(n: int, oracle: QuantumCircuit) -> QuantumCircuit:
"""DJ circuit. `oracle` acts on n input qubits + 1 ancilla qubit (indexed 0..n-1, n)."""
qc = QuantumCircuit(n + 1, n)
qc.x(n) # ancilla = |1⟩
qc.h(range(n + 1)) # H everywhere
qc.compose(oracle, inplace=True) # wire in the oracle
qc.h(range(n)) # H on inputs
qc.measure(range(n), range(n))
return qc
# --- Build two oracles for n = 3 ---
def constant_oracle(n: int, value: int) -> QuantumCircuit:
oc = QuantumCircuit(n + 1)
if value == 1:
oc.x(n)
return oc
def balanced_oracle(n: int, mask: int) -> QuantumCircuit:
"""f(x) = (mask · x) mod 2 — a family of balanced functions parameterized by `mask`."""
oc = QuantumCircuit(n + 1)
for q in range(n):
if (mask >> q) & 1:
oc.cx(q, n)
return oc
n = 3
sim = AerSimulator()
for name, oracle in [
("constant=0", constant_oracle(n, 0)),
("constant=1", constant_oracle(n, 1)),
("balanced(mask=0b101)", balanced_oracle(n, 0b101)),
("balanced(mask=0b111)", balanced_oracle(n, 0b111)),
]:
qc = deutsch_jozsa_circuit(n, oracle)
counts = sim.run(qc, shots=1).result().get_counts()
outcome = next(iter(counts))
verdict = "CONSTANT" if outcome == "0" * n else "BALANCED"
print(f"{name:<22s} → measured {outcome} → {verdict}")
# constant=0 → measured 000 → CONSTANT
# constant=1 → measured 000 → CONSTANT
# balanced(mask=0b101) → measured 101 → BALANCED
# balanced(mask=0b111) → measured 111 → BALANCED
Notice: when the balanced oracle is for some bitmask , the measurement returns exactly . That’s not a coincidence — it’s the seed of the next algorithm you’ll meet (Bernstein-Vazirani), where learning is the actual goal.
Why the separation isn’t quite as miraculous as it sounds
Two honest caveats:
- Against a randomized classical algorithm, Deutsch-Jozsa’s speedup evaporates. A classical algorithm that picks random ‘s and checks will be right with probability after queries. “Exponential speedup” only holds against deterministic classical algorithms with zero error.
- Oracle access is the whole game. In a real problem, you’d have to write as code anyway — and if you have the code, you could inspect it directly. The separation is a statement about query complexity in the black-box model, not wall-clock time on any real problem.
So why does anyone teach Deutsch-Jozsa? Because it introduces, cleanly and irrefutably, the three moves that power every subsequent quantum algorithm: oracle + phase kickback + Hadamard interference. Once you see them, you see them everywhere.
The deeper pattern: Hadamard transforms and Fourier analysis
The final in DJ is the discrete Fourier transform over the group . The algorithm is, structurally:
- Prepare a uniform superposition over the group .
- Apply the oracle to introduce a character (a sign pattern) onto the group.
- Fourier-transform to read out a single Fourier coefficient.
Every algorithm we’ll meet in this track follows the same three-move shape, with different groups and different characters. Simon uses with a shift character. Shor uses with a phase character and the QFT in place of Hadamards. QPE uses with a phase character directly.
Exercises
1. Verify the unitary
The oracle for (the CNOT oracle in Deutsch ) is a matrix. Write it out and verify .
Show answer
CNOT with control = qubit 0, target = qubit 1, in the basis = :
follows from CNOT being its own inverse.
2. Hand-trace
Pick the balanced oracle (i.e., CNOT from to ancilla, then CNOT from to ancilla). Write the state after the oracle as a superposition over with explicit signs. Predict the measurement outcome.
Show answer
. After phase kickback, the input register (ignoring ancilla) is
This is times — wait, factor it: .
Apply : . So the measurement returns 11 with certainty. Indeed, the “secret” string is s = 11 (both bits contribute), and DJ spits it out.
3. Build a non-linear balanced oracle
The mask-based oracle only produces balanced functions of the form . Can you construct a balanced oracle that isn’t linear? (Hint: any balanced function can be encoded as a truth-table oracle using Toffoli-based construction.)
Show sketch
A simple nonlinear balanced function on : (this is balanced because exactly 4 of 8 inputs have … wait, that’s 2 not 4. Let me pick a different one).
: evaluate at all 8 inputs; 4 outputs are 0 and 4 are 1. Implement by ccx q[1], q[2], q[n]; cx q[0], q[n];. Test with DJ — any non- outcome confirms balanced.
4. Simulate the query complexity
For , classically it could take up to queries to be certain. Write a classical worst-case simulation that finds a function where it takes exactly this many queries. Then run DJ on it and confirm the one-query result.
Hint
Construct a balanced function that agrees with “constant = 0” on the first 128 inputs and outputs 1 on the remaining 128. A deterministic classical algorithm querying in order 0, 1, 2, … sees 128 zeros before finding a 1. DJ still uses 1 query.
What you should take away
- Deutsch-Jozsa separates constant from balanced with one quantum query, where classical deterministic algorithms need .
- Phase kickback converts an oracle that computes into one that multiplies the input register by .
- Hadamard-sandwich structure: prepare uniform superposition, oracle, Hadamard back, read out one Fourier coefficient. This pattern repeats in every algorithm in this track.
- The speedup is against deterministic classical algorithms in the query model. Against randomized algorithms the gap shrinks or vanishes.
Next: Bernstein-Vazirani and Simon — the algorithms that take the Deutsch-Jozsa framework and turn it into something you can actually recognize as “learning something.”