Skip to content
Tech Interview Prep
Technical interview guide

Quantum Algorithms I: Deutsch-Jozsa & Grover's Search

The foundational oracle-based algorithms that first demonstrated provable quantum speedups: exponential for Deutsch-Jozsa, quadratic for Grover's search.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v3
Editorial status
Reviewed

Scope: IBM Quantum learning and Qiskit current algorithm documentation; original Deutsch-Jozsa, Grover, BBHT, and query lower-bound literature reviewed 2026-09-04.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

How does the quantum black-box query model differ from classical query complexity, and how is an oracle represented as a unitary transformation?

Answer

The 90-second answer. Classical query complexity counts how many times an algorithm evaluates a black-box function $f: {0,1}^n \to {0,1}^m$ on a single input $x$. Quantum query complexity counts how many times it applies a unitary $U_f$ instead. The difference that matters: $U_f$ acts on a superposition $\sum_x \alpha_x |x\rangle$, so one query touches all $2^n$ inputs at once, but you cannot read out all $2^n$ values, because measurement collapses the state. The oracle is unitary because quantum evolution is reversible; the standard encoding is the bit-flip oracle $U_f|x\rangle|y\rangle = |x\rangle|y \oplus f(x)\rangle$, and for Boolean $f$ the phase oracle $S_f|x\rangle = (-1)^{f(x)}|x\rangle$ is equivalent to it via phase kickback. Query complexity is a lower-bound tool: it counts oracle calls and deliberately ignores the cost of building the oracle.

Assumptions to state. $f$ is a black box: the algorithm may not inspect its circuit. We count oracle invocations, not gates. The oracle is given for free; whether it can be built cheaply is a separate question, and the one that decides whether a query speedup becomes a wall-clock speedup.

Why the oracle must be unitary. A map $|x\rangle \to |f(x)\rangle$ is not reversible when $f$ is non-injective: distinct basis states would collide, orthogonality would be destroyed, and the map would not be unitary. XOR-ing the result into an ancilla keeps the joint map a permutation, hence unitary, and self-inverse for Boolean $f$: $U_f^2 = I$.

Phase kickback, traced. Take $f(x) = x$ on one qubit and target $|-\rangle = (|0\rangle - |1\rangle)/\sqrt{2}$. Query with $x = 1$:

$$U_f |1\rangle|-\rangle = |1\rangle \frac{|0 \oplus 1\rangle - |1 \oplus 1\rangle}{\sqrt{2}} = |1\rangle \frac{|1\rangle - |0\rangle}{\sqrt{2}} = -|1\rangle|-\rangle.$$

The target is unchanged and the phase $(-1)^{f(1)} = -1$ has moved onto the input register. That is why a phase oracle needs no ancilla: it is the bit-flip oracle with the ancilla factored out.

DimensionClassical query modelQuantum query model (unitary oracle)
State spaceStrings $x \in {0,1}^n$Hilbert space of dimension $2^n$
Query inputOne sample $x$ (deterministic or randomized)Superposition $\sum_x \alpha_x
TransformationArbitrary map $f(x)$Unitary $U_f$, $U_f^\dagger U_f = I$
ReadoutExact value $f(x)$Measurement only; interference happens before readout
Cost metricSequential evaluationsOracle calls (gate cost counted separately)

Where the separation shows up. Deutsch–Jozsa: 1 query quantum vs $2^{n-1}+1$ classical deterministic. Bernstein–Vazirani: 1 vs $n$. Grover: about $(\pi/4)\sqrt{N}$ queries vs $N/2$ classical for a search over $N$ items. At $N = 10^6$ that is roughly 785 queries against 500,000.

Failure modes. (1) Query complexity is not time complexity: if $U_f$ must be compiled from a circuit of size $s$, each query costs $O(s)$ gates, and a $\sqrt{N}$ query speedup can be eaten by a large $s$. (2) The oracle is not free, if the input is given explicitly rather than as a black box, query complexity says nothing about the real problem. (3) You cannot read out $f(x)$ for all $x$; the algorithm must arrange interference so the answer survives measurement. (4) Non-Boolean $f$ needs $m$ ancilla qubits, one per output bit.

Python
import numpy as np

# Bit-flip unitary for f(x) = x on 1 input qubit + 1 target qubit:
# |x, y> -> |x, y ^ x>, i.e. CNOT (control = input, target = ancilla)
U_f = np.array([
    [1, 0, 0, 0],  # |00> -> |00>
    [0, 1, 0, 0],  # |01> -> |01>
    [0, 0, 0, 1],  # |10> -> |11>
    [0, 0, 1, 0],  # |11> -> |10>
], dtype=complex)
assert np.allclose(U_f @ U_f.conj().T, np.eye(4))  # unitary
assert np.allclose(U_f @ U_f, np.eye(4))           # self-inverse

# Phase oracle on the input register: S_f = diag((-1)^0, (-1)^1) = Z
S_f = np.array([[1, 0], [0, -1]], dtype=complex)
assert np.allclose(S_f @ S_f.conj().T, np.eye(2))

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

Why must quantum oracles be reversible unitaries, and how do you implement a classical boolean function f(x) reversibly without leaving uncomputed garbage entangled with the output?

Answer

The 60-second answer. A closed quantum system evolves by a unitary $U$ with $U^\dagger U = I$: linear, inner-product preserving, invertible. A classical function $f:{0,1}^n \to {0,1}$ is many-to-one, so it cannot be a unitary on $n$ qubits. Unitaries are bijections on state space, and linearity forbids the copy you would need to keep $x$ around (no-cloning). The fix is to make the map injective by carrying the input and XORing into a target:

$$U_f |x\rangle |y\rangle = |x\rangle |y \oplus f(x)\rangle$$

XOR is an involution, so $U_f^2 = I$ and $U_f = U_f^\dagger$: the oracle is its own inverse and therefore unitary. The catch is ancillas. Any circuit that computes $f$ from Toffoli/AND gates leaves intermediate values in scratch qubits, and those garbage bits entangle with $x$. In a superposition the garbage is a which-path record, and the interference Deutsch–Jozsa, Grover and phase estimation depend on dies. Compute–copy–uncompute removes it.

Why garbage kills the algorithm

Synthesizing $f$ from standard gates needs scratch ancillas $|g_k\rangle$. Left populated, the unitary produces

$$U_\text{dirty} |x\rangle |0\rangle |0\rangle_g = |x\rangle |f(x)\rangle |g(x)\rangle_g$$

For an input superposition $\sum_x |x\rangle$, the ancilla becomes entangled with the query register. Tracing it out leaves the query register in a mixed state, and interference between $|x\rangle$ and $|x'\rangle$ collapses whenever $\langle g(x) | g(x') \rangle = 0$. The ancilla has effectively measured which path was taken.

Compute–copy–uncompute

Use three registers: input $|x\rangle$, target $|y\rangle$, clean scratch $|0\rangle_g$.

|x> ───────■─────────────■─────── |x>
           │             │
|0>_g ──[Compute]───■───[Compute]† |0>_g
                    │
|y> ────────────────X──────────── |y ⊕ f(x)>
  1. Compute: $V |x\rangle |0\rangle |0\rangle_g = |x\rangle |0\rangle |g(x), f(x)\rangle_g$.
  2. Copy: CNOT the computed bit into the target: $|x\rangle |y \oplus f(x)\rangle |g(x), f(x)\rangle_g$. The CNOT copies only a computational-basis value, so no-cloning is not violated.
  3. Uncompute: apply $V^\dagger$ to $|x\rangle$ and the scratch register, returning it to $|0\rangle_g$.

Net: $U_f |x\rangle |y\rangle |0\rangle_g = |x\rangle |y \oplus f(x)\rangle |0\rangle_g$. The scratch factors out as a product state and can be reused or traced out without decohering the query register.

The trade-offs an interviewer will push on

  • Phase oracle: no ancilla at all. If the algorithm only needs $f$ as a phase, $|x\rangle \mapsto (-1)^{f(x)}|x\rangle$, implement it directly as a diagonal unitary (a multi-controlled $Z$ for $f = \text{AND}$) and skip the target register and the uncompute entirely. Cost: it only works where the algorithm accepts phase kickback; you can no longer read $f$ into a register.
  • Dirty ancillas. You do not need ancillas initialized to $|0\rangle$. Dirty-ancilla constructions borrow qubits in an arbitrary unknown state, use them, and restore them to that same state, so they factor out again. Cost: more gates than the clean version, and the restoration must be exact. Any residual correlation with $x$ is the same garbage problem.
  • Measurement-based uncomputation. Instead of running $V^\dagger$, measure the scratch register in the computational basis and apply a classically-controlled Pauli correction to the remaining qubits. This replaces the second half of the circuit with measurement plus feed-forward, converting coherent depth into classical latency. It is the standard choice in surface-code/lattice-surgery settings where measurement is cheap and coherent depth is not.
  • Bennett's peephole / checkpointing. Full uncompute costs roughly twice the gates and twice the depth of the compute circuit. Bennett's peephole optimization keeps only a subset of intermediate states and recomputes the segments between them, trading extra time for fewer live ancillas. The curve is circuit-dependent; "uncompute everything" is the space-cheap end, not the only option.

Failure mode and detection. Skip the uncompute and the query register's reduced density matrix is mixed; in Grover the marked-state amplitude fails to grow as predicted. Detect it by simulating a small instance and checking the scratch register is left in $|0\rangle$ (equivalently, that the query register's reduced state is pure), or by comparing the measured success probability against the ideal oracle. One more cost worth naming: uncompute needs the circuit $V$, not just a truth table. A truth-table oracle on $n$ qubits is a different, much larger construction.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

How does preparing an ancilla in the |-⟩ state convert a bit-flip oracle |x⟩|y⟩ → |x⟩|y ⊕ f(x)⟩ into a phase oracle |x⟩ → (-1)^f(x)|x⟩ via phase kickback?

Answer

The 60-second answer

The oracle applies $X$ to the ancilla exactly when $f(x)=1$: $U_f|x\rangle|y\rangle = |x\rangle X^{f(x)}|y\rangle$. Prepare the ancilla in $|-\rangle$, the eigenvector of $X$ with eigenvalue $-1$. Then $X^{f(x)}|-\rangle = (-1)^{f(x)}|-\rangle$, and that eigenvalue is a scalar, so it slides off the ancilla onto the input register:

$$U_f|x\rangle|-\rangle = (-1)^{f(x)}|x\rangle|-\rangle.$$

The ancilla is left in $|-\rangle$ and stays product-separable with the input, so it can be reused. The sign is a relative phase between branches of the input register, so it only does work when $|x\rangle$ is in superposition: on a single basis state it is a global phase and unobservable.

Why the eigenvalue must be $-1$

| ancilla $|y\rangle$ | after $U_f$, $f(x)=0$ | after $U_f$, $f(x)=1$ | kickback? | | :--- | :--- | :--- | :--- | | $|0\rangle$ | $|0\rangle$ | $|1\rangle$ | no: ancilla flips, input untouched | | $|1\rangle$ | $|1\rangle$ | $|0\rangle$ | no | | $|+\rangle$ | $|+\rangle$ | $|+\rangle$ | no: eigenvalue $+1$, phase is global | | $|-\rangle$ | $|-\rangle$ | $-|-\rangle$ | yes: eigenvalue $-1$ |

$|+\rangle$ is the $+1$ eigenvector, so both branches come out identical and nothing is kicked back. $|0\rangle$ and $|1\rangle$ are not eigenvectors at all: the ancilla flips and the input learns nothing.

Worked trace: parity oracle on two qubits

Take $f(x) = x_0 \oplus x_1$, built as CNOT$(x_0 \to a)$ then CNOT$(x_1 \to a)$, with the ancilla starting in $|-\rangle$. Each CNOT contributes $(-1)^{x_i}$ because $X|-\rangle = -|-\rangle$, so the pair contributes $(-1)^{x_0 \oplus x_1}$ and the ancilla returns to $|-\rangle$.

Input $(|00\rangle+|01\rangle+|10\rangle+|11\rangle)/2$ becomes

$$\tfrac{1}{2}\big(|00\rangle - |01\rangle - |10\rangle + |11\rangle\big) \otimes |-\rangle.$$

Check each branch: $f(00)=0 \to +$, $f(01)=1 \to -$, $f(10)=1 \to -$, $f(11)=0 \to +$. The ancilla is back in $|-\rangle$ with no uncompute step, because this ladder is its own inverse on the ancilla. For a general input, $U_f\big(\sum_x c_x|x\rangle\big)|-\rangle = \big(\sum_x (-1)^{f(x)} c_x |x\rangle\big)|-\rangle$.

Failure modes

  1. Wrong ancilla state. $|+\rangle$ gives eigenvalue $+1$ for both values of $f$, so no relative phase appears. Deutsch–Jozsa returns a uniform distribution where a deterministic answer is expected, and Grover's diffusion operator has nothing to amplify. Detection: run the circuit on a constant $f$ and check the output is deterministic.

  2. Partial ancilla preparation. With ancilla $a|0\rangle + b|1\rangle$ and $a \neq -b$, the post-oracle ancilla is $a|f(x)\rangle + b|1 \oplus f(x)\rangle$, which depends on $f(x)$: the ancilla entangles with the input. Tracing it out or measuring it decoheres the input register and the interference pattern washes out. Only $a = -b$ makes the two branches identical up to sign.

  3. Ancilla decoherence or mid-circuit measurement. Same mechanism: the relative phase degrades into a random classical sign per branch. Detection: repeat the circuit; a run-to-run varying sign on a deterministic instance is the signature.

  4. Cost. The bit-flip oracle needs an extra wire plus the CNOT/Toffoli ladder that decomposes $f$; a direct phase oracle $R_f|x\rangle = (-1)^{f(x)}|x\rangle$ needs neither. The ancilla itself is a catalyst: returned to $|-\rangle$, reusable across oracle calls, so the real cost is the gate decomposition of $f$, not the wire.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-11

Design and validate a quantum query workflow for phase oracle.

Answer

Core answer (first 90 seconds). Assume f: {0,1}^n → {0,1} arrives as a reversible circuit, n is small enough to simulate exhaustively (n ≤ 12, 4096 basis states), and you have one spare ancilla. The phase oracle is U_f|x⟩ = (−1)^{f(x)}|x⟩ with every ancilla back in |0⟩ at exit. Build it as compute–phase–uncompute: allocate one ancilla, compute f(x) into it with a multi-controlled X, apply a single Z to that ancilla, then run the compute circuit in reverse. The Z's phase kicks back through the compute circuit onto the data register; the uncompute returns the ancilla to |0⟩, so the sign is left attached to the data register alone. Wrap that in H^⊗n, your Grover iterations, and the diffusion operator.

Why it works. After compute the joint state is |x⟩|f(x)⟩. Z on the ancilla multiplies it by (−1)^{f(x)}. Uncompute maps the ancilla back to |0⟩, giving (−1)^{f(x)}|x⟩|0⟩: the sign now lives on the data qubits. This is phase kickback: conjugating Z by the compute circuit C turns it into diag((−1)^{f(x)}) on the data register (with the ancilla starting in |0⟩). What you don't need is the |−⟩ preparation of the ancilla.

Circuit (Qiskit 1.x).

Python
from qiskit import QuantumCircuit
from qiskit.quantum_info import Operator, Statevector
import numpy as np

n = 3
def f(x): return int(x == 5)          # mark |101>

def phase_oracle(n, f):
    qc = QuantumCircuit(n + 1)        # n data + 1 ancilla
    comp = QuantumCircuit(n + 1)
    for x in range(2**n):
        if f(x):
            for i in range(n):
                if not (x >> i) & 1: comp.x(i)
            comp.mcx(list(range(n)), n)
            for i in range(n):
                if not (x >> i) & 1: comp.x(i)
    qc.compose(comp, inplace=True)
    qc.z(n)
    qc.compose(comp.inverse(), inplace=True)
    return qc

Trace, n=3, f(x)=(x==5). |101⟩|0⟩ → compute → |101⟩|1⟩ → Z → −|101⟩|1⟩ → uncompute → −|101⟩|0⟩. Every other basis state is untouched, e.g. |000⟩|0⟩ → |000⟩|0⟩. So U_f|101⟩ = −|101⟩ and U_f|000⟩ = |000⟩.

Validation. Simulate the statevector and check every basis state against the definition; this catches polarity, ancilla leakage and spurious global phase in one pass:

Python
U = Operator(phase_oracle(n, f))
for x in range(2**n):
    psi = Statevector.from_int(x, 2**(n+1))   # |x>|0>
    out = psi.evolve(U)
    assert np.allclose(out.data, (-1)**f(x) * psi.data, atol=1e-12)

Because the assertion demands out == ±psi exactly, it also proves the ancilla returns to |0⟩. On hardware the exact equality becomes a fidelity check; set the threshold from the device's measured two-qubit error and the oracle's two-qubit gate count: with per-gate error p and g two-qubit gates, F ≈ (1−p)^g, so p = 1e-2 and g = 20 gives F ≈ 0.82 (illustrative arithmetic, not a device spec).

Trade-offs. Two ways to turn a reversible compute circuit C (C|x⟩|0⟩ = |x⟩|f(x)⟩) into a phase oracle:

FormGatesAncilla at exit
Compute–Z–uncompute, C† Z C2 compute circuits + 1 Z|0⟩
|−⟩ trick: ancilla in H|1⟩, apply C once1 compute circuit + 2 H|−⟩

Pick the |−⟩ form when the ancilla can stay in |−⟩ and gate count matters. Pick the sandwich when the ancilla must return to |0⟩: e.g. it is shared with surrounding logic, or when the oracle must be independent of the ancilla's input state.

Synthesis: exact (one multi-controlled X per marked x, O(m·n) Toffolis for m marked states, O(n) per multi-controlled gate with ancillas) is readable and fine for small n. Phase-polynomial synthesis expresses the oracle as phase gadgets; a gadget with k controls costs O(k) T gates, so total T-count scales with the number of terms: use it when T-count dominates on fault-tolerant hardware.

Failure modes and detection. Wrong predicate polarity marks the complement and Grover amplifies the wrong set: caught by the exhaustive loop. Phase on garbage (ancilla not clean at exit) entangles ancilla with data and breaks interference: caught by the same loop, since out must equal ±psi. Uncompute omitted leaves f(x) in the ancilla: caught by checking the ancilla's reduced state is |0⟩. Invalid states marked (f defined off-domain): add a domain assertion on x. Global phase mistaken for selective marking (U_f = −I instead of diag((−1)^{f(x)})): check U_f|0⟩ = |0⟩ whenever f(0)=0.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

How does the Deutsch-Jozsa algorithm determine whether a function is constant or balanced in a single query?

Answer

The 60-second version

This is a promise problem. I get black-box access to f: {0,1}^n → {0,1}, and I'm promised f is either constant (same output on every input) or balanced (0 on exactly half the inputs, 1 on the other half). I have to say which. My answer: one call to the oracle, and I read the verdict off whether the data register comes back as all zeros.

The mechanism is phase kickback. Put the n data qubits in |0...0⟩ and one ancilla in |1⟩, then Hadamard all n+1. The data register becomes a uniform superposition over all 2^n inputs; the ancilla becomes |−⟩ = (|0⟩ − |1⟩)/√2. The oracle computes |x⟩|y⟩ → |x⟩|y ⊕ f(x)⟩. Applied to |−⟩ that is |x⟩|−⟩ → (−1)^f(x) |x⟩|−⟩: the ancilla is untouched and f(x) lands as a phase on the data register. The state is now (1/√2^n) Σ_x (−1)^f(x) |x⟩.

Hadamard the data register again. The amplitude on |0...0⟩ is (1/2^n) Σ_x (−1)^f(x). If f is constant, every term has the same sign, the sum is ±2^n, and the amplitude is ±1: I measure all zeros with certainty. If f is balanced, exactly 2^(n−1) terms are +1 and 2^(n−1) are −1, the sum is exactly zero, and all-zeros never appears. So all zeros means constant; any 1 bit means balanced. One query, deterministic.

What a senior candidate should add

The exponential speedup is real but narrow, and it's against the wrong baseline. It separates DJ from a deterministic classical algorithm, which needs 2^(n−1) + 1 queries in the worst case. A randomized classical algorithm does far better: sample random inputs, and if you ever see two different outputs, f is balanced. For a balanced f each query returns 0 with probability 1/2, so the chance that k queries all agree is 2^(1−k). Ten random queries give an error around 0.2%. Ten classical queries versus one quantum query is a constant-factor win, not an exponential one. The exponential separation exists only against deterministic classical.

Second: DJ has no practical application. The promise is artificial, and the query model doesn't charge you for building U_f. If f arrives as a classical circuit, you have to compile it into a reversible quantum circuit, and that circuit is usually far more expensive than the 2^(n−1) + 1 classical queries you were trying to beat. Query complexity is not gate complexity.

Third: the promise is load-bearing. If f is neither constant nor balanced, the algorithm still returns a bitstring and gives you no signal that the promise was violated. There is no self-check built in.

Fourth, the one that bites in practice: the balanced case depends on exact cancellation of 2^n amplitudes. Any gate error, decoherence, or imperfect oracle breaks that cancellation and leaks amplitude into |0...0⟩, so a balanced f can be misread as constant. The constant case is robust, because the amplitude is concentrated on a single basis state. The errors are asymmetric: noise manufactures false "constant" verdicts. The way to catch it is to run the circuit on a known-balanced f and confirm the all-zeros rate stays at zero.

Where it matters

DJ is the ancestor of the hidden-subgroup family: Bernstein-Vazirani, Simon, and eventually Shor. Its value is as the cleanest demonstration that phase kickback plus interference can extract a global property of f in one query. If someone actually asks you to decide constant-versus-balanced on a real function, sample randomly; DJ is the wrong tool.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

How does the Deutsch algorithm differ from Deutsch-Jozsa, and why does Deutsch-Jozsa yield an exponential separation in exact query complexity but not under bounded error?

Answer

The Deutsch algorithm evaluates a boolean function on a single bit, $f: {0,1} \to {0,1}$, determining whether $f(0) = f(1)$ (constant) or $f(0) \neq f(1)$ (balanced). Deutsch-Jozsa generalizes this domain to $n$ bits, $f: {0,1}^n \to {0,1}$, under the promise that $f$ is either constant (all inputs yield 0 or all yield 1) or balanced (exactly $2^{n-1}$ inputs yield 0 and $2^{n-1}$ yield 1).

Both algorithms use exactly one evaluation of the quantum phase oracle $U_f |x\rangle = (-1)^{f(x)} |x\rangle$ (typically obtained via phase kickback using an ancilla prepared in $|-\rangle$). In Deutsch-Jozsa, uniform superposition over $n$ register qubits is prepared by $H^{\otimes n} |0\rangle^{\otimes n}$. Applying $U_f$ followed by a second Hadamard transform $H^{\otimes n}$ yields the state:

$$|\psi\rangle = \frac{1}{2^n} \sum_{y \in {0,1}^n} \left( \sum_{x \in {0,1}^n} (-1)^{f(x) \oplus (x \cdot y)} \right) |y\rangle$$

The amplitude of the all-zero state $|0\rangle^{\otimes n}$ is $\frac{1}{2^n} \sum_{x} (-1)^{f(x)}$. If $f$ is constant, $(-1)^{f(x)}$ is identical for all $2^n$ terms, so the amplitude is $\pm 1$, giving probability 1 of measuring $|0\rangle^{\otimes n}$. If $f$ is balanced, the sum of $+1$ and $-1$ terms cancels exactly to 0. A single quantum query distinguishes the two cases with zero error (Exact Quantum Query Complexity $Q_E(f) = 1$).

The Query Complexity Gap

The exponential speedup appears strictly in the deterministic/exact comparison:

  1. Deterministic Classical ($D(f)$): In the worst case, a classical deterministic algorithm must inspect more than half of the total domain $N = 2^n$ before it can guarantee the function is constant rather than balanced. If it inspects $2^{n-1}$ inputs and all evaluate to 0, the next input could still be 1 (balanced) or 0 (constant). Thus, $D(f) = 2^{n-1} + 1 = O(2^n)$. Comparing $Q_E(f) = 1$ to $D(f) = 2^{n-1} + 1$ produces an exponential separation: $O(1)$ vs $\Omega(2^n)$.

  2. Bounded-Error Randomized Classical ($R_\epsilon(f)$): The exponential separation vanishes if randomized sampling with bounded error $\epsilon$ is allowed. Suppose $k$ independent, uniformly distributed inputs $x_1, x_2, \dots, x_k$ are queried. If $f$ is balanced, the probability that all $k$ evaluations yield identical values is:

$$P(\text{all identical} \mid f \text{ balanced}) = 2 \cdot \left(\frac{1}{2}\right)^k = 2^{-(k-1)}$$

Setting $2^{-(k-1)} \le \epsilon$ requires only $k = 1 + \lceil \log_2(1/\epsilon) \rceil$ queries. For an error bound of $\epsilon \le 1/3$, $k = 3$ classical queries suffice regardless of $n$. Hence, $R(f) = O(1)$ and $BPP = BQP = O(1)$ query complexity for this promise problem.

ModelQuery ComplexityAsymptotic Behavior
Exact Quantum ($Q_E$)$1$$O(1)$
Bounded-Error Quantum ($Q_2$)$1$$O(1)$
Deterministic Classical ($D$)$2^{n-1} + 1$$\Omega(2^n)$ (Exponential)
Randomized Classical ($R$)$\lceil \log_2(1/\epsilon) \rceil + 1$$O(1)$ (No separation vs quantum)

Pitfalls and Edge Cases

  • Promise Violations: If $f$ is neither constant nor balanced (e.g., $2^{n-1} - 1$ zeros), constructive/destructive interference at $|0\rangle^{\otimes n}$ is incomplete; measuring non-zero no longer guarantees balance.
  • Transpilation Overhead: Although query count is 1, circuit depth and 2-qubit gate count scale with the oracle construction $U_f$. A physical realization of an arbitrary $n$-qubit oracle can require up to $O(2^n)$ elementary gates.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

Design and validate a quantum query workflow for Deutsch-Jozsa interference.

Answer

I'd clarify the promise first: f:{0,1}^n -> {0,1} is either constant or balanced, and the oracle is a coherent unitary U_f:|x>|y> -> |x>|y xor f(x)>. Under those assumptions the workflow is one oracle query: prepare n query qubits in |0>, ancilla in |1>, apply H to all n+1 qubits, apply U_f, apply H to the n query qubits, measure them. The ideal result is deterministic: all zeros for constant, never all zeros for balanced.

The mechanism is phase kickback plus Hadamard interference. After the first H layer the state is (1/sqrt(2^n)) sum_x |x> ⊗ (|0>-|1>)/sqrt(2). The oracle writes f(x) into the ancilla, but because the ancilla is in |->, that flips its sign: U_f gives (1/sqrt(2^n)) sum_x (-1)^f(x) |x>|->. The final H on the query register maps this to an amplitude on |0>^n of (1/2^n) sum_x (-1)^f(x). If f is constant, every term has the same sign, so the sum is ±2^n and the amplitude is ±1. If f is balanced, exactly half the terms are +1 and half are -1, so the sum is 0. That is why one query decides the promise exactly.

A worked trace for n=3: f(x)=x0 xor x1 xor x2 is balanced. The eight values of (-1)^f(x) are four +1 and four -1, so the sum is 0 and P(0^3)=0. The constant f=0 gives eight +1 terms, sum 8, amplitude 8/8=1, P(0^3)=1. A non-promised function with five zeros and three ones gives sum 5-3=2, amplitude 2/8=0.25, P(0^3)=0.0625, so the outcome is not deterministic.

For validation, I'd exhaustively simulate n=3. There are 2 constant oracles and C(8,4)=70 balanced oracles, 72 promised functions total. For each, assert P(0^3)=1 for constant and P(0^3)=0 for balanced. Then simulate all 256 functions from 3 bits to 1 bit and confirm the non-promised ones do not produce 0 or 1. On hardware, run 4096 shots: constant should show all zeros, balanced should show no all-zero outcomes. Compare any deviation to a readout-error calibration; if constant has nonzero outcomes above that baseline, or balanced has all-zero outcomes above it, flag the run. The circuit uses n+1 H gates before the oracle, n H gates after it, one oracle call, and n measurements. For n=3 that is 4 H before, 3 H after, one oracle, 3 measurements.

The trade-off is classical versus quantum query count. Classically, deterministic worst case needs 2^(n-1)+1 queries. Randomized classical needs about 1+log2(1/delta) queries for error delta; for delta=0.01 that is 8 queries. Quantum needs one query, but it requires a coherent oracle and error correction. I'd choose quantum when the oracle is already coherent and n is large; I'd choose classical when the oracle is a cheap classical black box or n is small enough that 2^(n-1)+1 is acceptable.

Failure modes and detection:

  • Measuring the query register before the final H destroys the interference. Detection: a constant oracle gives roughly uniform counts instead of all zeros.
  • Ancilla not in |->, for example |1> without the H, loses phase kickback. Detection: constant oracle again gives uniform query outcomes.
  • Non-promised function. Detection: exhaustive small-n simulation shows P(0^n) strictly between 0 and 1.
  • Noise called deterministic. Detection: 4096-shot run with constant oracle shows nonzero outcomes above readout-error baseline.
  • Bit order reversed when building the oracle from a truth table. The promise is preserved, so the DJ decision still works, but validation of that specific oracle fails. Detection: compare the simulated truth table against the intended one before trusting the run.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Design and validate a quantum query workflow for DJ query advantage.

Answer

Clarify, then assume. Deutsch–Jozsa is a promise problem, not a search. You get f: {0,1}^n → {0,1} as a black-box oracle, promised that f is either constant (same value on all 2^n inputs) or balanced (0 on exactly half). "Does DJ give advantage" has no answer until you name the classical model you're comparing against, because the separation is deterministic-classical vs quantum, not randomized-classical vs quantum.

Core answer: the workflow is one oracle call. Prepare n input qubits in |0⟩ and one ancilla in |1⟩. Hadamard all n+1. Apply U_f: |x⟩|y⟩ → |x⟩|y⊕f(x)⟩. Hadamard the n input qubits. Measure them. All zeros → constant; anything else → balanced. Deterministic, exact, one query.

Trace it for n=2 with f(x)=x₁⊕x₂ (balanced). After H on all three qubits the state is (1/2)Σₓ|x⟩ ⊗ (|0⟩−|1⟩)/√2. Phase kickback turns the ancilla into a sign: (1/2)Σₓ(−1)^{f(x)}|x⟩ ⊗ (|0⟩−|1⟩)/√2. For f=x₁⊕x₂, Σₓ(−1)^{x₁⊕x₂}|x₁x₂⟩ = (|0⟩−|1⟩)⊗(|0⟩−|1⟩). H⊗H maps that to 2|11⟩. Measuring 11 ≠ 00 → balanced. Swap in f=0 and the same steps give 2|00⟩ → constant.

The numbers that decide it. Take n=100. Deterministic classical exact needs 2^{n−1}+1 = 2^99+1 ≈ 6.3×10^29 queries in the worst case. Quantum: 1. That exponential gap is real. But randomized classical with error ε needs only ⌈1+log₂(1/ε)⌉ queries: 21 for ε=10⁻⁶, independent of n. So if your baseline is a bounded-error randomized algorithm, DJ's advantage is 1 vs 21, not 1 vs 10^29. Name the baseline or the claim is wrong.

When it isn't worth it. Count gates, not just queries. U_f must be compiled into reversible gates; if f is given as a circuit of size s, U_f costs O(s) and the quantum run is O(s+n) gates: the same order as one classical evaluation. The query separation survives; the wall-clock separation usually doesn't. And the promise is doing the work: drop it and DJ's output is uniform garbage.

Failure modes and how you catch them.

  • Promise violated. DJ returns a uniformly random bit. Catch it by brute-forcing the promise for n≤4 in test, and by validating the input generator in production.
  • Wrong baseline. Claiming exponential advantage over randomized classical. Catch it by writing the randomized bound next to the claim.
  • Gate cost ignored. Catch it by compiling U_f and counting Toffoli/T gates against the classical circuit size.
  • Oracle embedded wrong: missing ancilla, non-reversible embedding, or a phase oracle without kickback. Catch it by running n=1,2,3 against known f and checking the full output distribution, not just the modal answer.
  • Toy result called supremacy. n=3 on a simulator beats a 5-query classical bound on a laptop. Catch it by refusing to call anything supremacy below the regime where the classical bound is actually infeasible.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

Design and validate a quantum query workflow for DJ output decoding.

Answer

Core answer (first 90 seconds). Deutsch–Jozsa decides whether a promised f:{0,1}^n→{0,1} is constant or balanced with one oracle query. The verdict is read from the n input qubits alone: measure them in the computational basis; all-zeros means constant, any nonzero string means balanced. The ancilla is never measured: after the oracle it sits in |−⟩ and would read 1 on every shot.

Assumptions to state before you draw anything: f satisfies the constant-or-balanced promise; the oracle is a bit oracle U_f|x⟩|y⟩ = |x⟩|y⊕f(x)⟩; the ancilla starts in |1⟩ and is Hadamarded into |−⟩ so the oracle kicks back a phase (−1)^{f(x)}.

Circuit: n input qubits plus one ancilla. X(ancilla), H on all n+1, oracle, H on the n input qubits only, measure the n input qubits. The ancilla is left unmeasured.

Python
from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator

def dj(n, oracle):
    qc = QuantumCircuit(n + 1, n)
    qc.x(n)                                   # ancilla -> |1>
    qc.h(list(range(n + 1)))                  # |0..0>|1> -> |+..+>|->
    qc.compose(oracle, qubits=list(range(n + 1)), inplace=True)
    qc.h(list(range(n)))                      # input register only
    qc.measure(list(range(n)), list(range(n)))
    return qc

def const0(n):  return QuantumCircuit(n + 1)              # f(x)=0
def bal_x0(n):
    o = QuantumCircuit(n + 1); o.cx(0, n); return o       # f(x)=x_0
def bal_parity(n):
    o = QuantumCircuit(n + 1)
    for i in range(n): o.cx(i, n)
    return o                                              # f(x)=x_0^...^x_{n-1}

sim = AerSimulator()
for name, o in [("const0", const0(3)), ("bal_x0", bal_x0(3)), ("bal_parity", bal_parity(3))]:
    counts = sim.run(dj(3, o), shots=1024).result().get_counts()
    print(name, "zeros:", counts.get("000", 0), "/1024")
# const0     zeros: 1024 /1024
# bal_x0     zeros: 0 /1024   (all 1024 shots on '001')
# bal_parity zeros: 0 /1024   (all 1024 shots on '111')

Worked trace (n=2, f(x)=x_0, CNOT q0→q2):

  1. |00⟩|0⟩ → X on q2 → |00⟩|1⟩.
  2. H on all three → (1/2)Σ_{x∈{0,1}²}|x⟩ ⊗ |−⟩.
  3. Oracle CNOT q0→q2 kicks back a phase → (1/2)Σ_x (−1)^{x_0}|x⟩|−⟩.
  4. H on q0,q1: amplitude at z is (1/4)Σ_x (−1)^{x_0 + x·z}, nonzero only at z_0=1, z_1=0.
  5. Measure → q0=1, q1=0. Qiskit prints the highest classical bit leftmost, so the string is '01'.
  6. OR of the bits is 1 → balanced.

Validation. The simulator sweep above is the first gate: constant oracles must return '000' on every shot, balanced oracles zero times. Add the parity oracle and confirm it also never returns '000'. On hardware, replace the single-shot rule with a fraction-of-zeros threshold:

Python
def classify(counts, shots, thresh=0.5):
    return "constant" if counts.get("000", 0) / shots > thresh else "balanced"

With per-qubit readout error p=0.01 and n=3, a constant oracle returns all-zeros with probability (1−p)³ = 0.9703, so the zero fraction sits at 0.97. A balanced oracle whose ideal output has one 1 bit returns all-zeros with probability p(1−p)² = 0.0098, so its zero fraction sits at 0.01. The 0.5 threshold is ~89 standard errors below the constant mean and ~159 above the balanced mean (SE = sqrt(μ(1−μ)/1024) ≈ 0.0053 and 0.0031). Hoeffding gives P(misclassify) ≤ 2exp(−2·1024·0.47²) ≈ 10^{−196} on the constant side. The naive "any nonzero → balanced" rule fails on hardware: P(at least one readout error in 1024 shots) = 1 − 0.9703^{1024} ≈ 1, so a constant oracle is always misread.

Failure modes.

  • Ancilla included in the decision. It is |−⟩, so it reads 1 every shot and every run looks balanced. Detect by running the constant oracle: it must return all-zeros.
  • Missing X on the ancilla. Ancilla starts |0⟩, H gives |+⟩, no phase kickback, output uniform, again always "balanced". Same detection.
  • Missing H on the ancilla. Ancilla stays |1⟩, the oracle XORs f(x) into it instead of kicking back a phase, output uniform. Same detection.
  • Single-shot decision on noisy hardware. One flipped bit turns a constant oracle into "balanced". Detect by comparing the 1024-shot zero fraction against the 0.5 threshold.
  • Promise violated. If f is neither constant nor balanced the output is meaningless. Detect by evaluating f on all 2^n inputs classically for small n (8 evaluations at n=3).
  • Oracle qubit-index mismatch. If the oracle's control/target indices don't match the circuit's, you decode a different f. Detect by comparing the measured string against the classically computed Walsh–Hadamard spectrum for small n.

Trade-offs. Endianness does not affect the verdict: the all-zeros string is invariant under bit reversal, so the OR-based decision is endian-safe; the convention only matters when you log which string you saw. Shot count is the cost knob: misclassification probability falls exponentially in shots (Hoeffding) while wall-clock rises linearly; 1024 shots is ample for n up to ~10 at p=0.01. The 0.5 threshold is optimal for equal priors and symmetric error; shift it if the priors are skewed. The same circuit with the input register measured in the computational basis is Bernstein–Vazirani, which reads off the secret string s directly; the classical deterministic lower bound for DJ is 2^{n−1}+1 queries (5 at n=3) against one quantum query.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Design and validate a quantum query workflow for Bernstein-Vazirani relation.

Answer

Assume the oracle is a black box for f(x) = s·x mod 2 with unknown s ∈ {0,1}^n, and "workflow" means: construct the oracle, run one query, decode the bitstring, and validate the chain against a classical reference. Core answer: H^⊗n|0⟩, phase oracle U|x⟩ = (−1)^{s·x}|x⟩, H^⊗n, measure. S with probability 1 in one query. Validation is a classical truth-table check plus a distribution check, because the algorithm cannot tell a linear oracle from an affine one.

Mechanism. H^⊗n|0…0⟩ = 2^{−n/2} Σ_x |x⟩. The phase oracle multiplies |x⟩ by (−1)^{s·x}. H is its own inverse, so H^⊗n applied to 2^{−n/2} Σ_x (−1)^{s·x}|x⟩ returns |s⟩ exactly: the Hadamard transform of the character (−1)^{s·x} is the delta at s. One query, deterministic outcome.

Workflow (Qiskit 1.x):

Python
from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator

def bv_oracle(qc, s):          # phase oracle, s[i] acts on qubit i
    for i, bit in enumerate(s):
        if bit == '1':
            qc.z(i)

def bv_circuit(s):
    n = len(s)
    qc = QuantumCircuit(n, n)
    qc.h(range(n)); bv_oracle(qc, s); qc.h(range(n))
    qc.measure(range(n), range(n))
    return qc

counts = AerSimulator().run(bv_circuit("110"), shots=1024).result().get_counts()
# {'011': 1024}

Trace, s="110" (s_0=1, s_1=1, s_2=0): H^⊗3|000⟩ is uniform; Z on qubits 0 and 1 multiplies |x⟩ by (−1)^{x_0+x_1}; the second H^⊗3 collapses to |q2 q1 q0⟩ = |011⟩. Qiskit reads qubit 0 as the least-significant bit, so the measured string is s reversed: decode with s = measured[::-1].

Validation, in order:

  1. Classical reference: f(x) = parity(x & s) for all 2^n x. Check f(0)=0 and f(e_i)=s_i; n+1 evaluations confirm linearity on the basis, which extends to all x by XOR.
  2. Promise check: verify f(x) = s'·x for the recovered s' over all x. This is the only place an affine offset f = s·x ⊕ 1 is caught: the algorithm sees it as a global phase and still returns s.
  3. Distribution: ideal statevector sim gives probability 1 on s. On hardware, take ~1000 shots; the modal outcome should dominate (standard error ≈ 1.6% at p=0.95). If no single outcome dominates, the oracle is not linear.

Failure modes:

failurehow it arisesdetection
non-linear oraclea general balanced f from DJ reusedmodal frequency drops from 1.0; top outcome O(n/2^n) for random f
decoder mismatchDJ decoder reused, reports "balanced"output is a full bitstring, not a constant/balanced flag
affine offsetstray X in the oracleinvisible to the algorithm; caught by f(0)=0
bit order reverseds[i] mapped to qubit n−1−imeasured string is s[::-1]; test a non-palindromic s
missing Z for a set bittypo in the oraclerecovered s differs in that bit; unit-test each e_i
query claim detachedoracle re-prepares or loopscount oracle calls in the transpiled circuit

Trade-offs. Phase oracle (Z gates, no ancilla) versus XOR oracle (CNOT onto an ancilla in |−⟩): the phase form is cheaper but only valid when the input register is in a basis state at the call; the XOR form composes. Exact statevector simulation (probability 1, no shots) versus shot sampling versus hardware (needs readout mitigation). Classical baseline: query f(e_i) for each i, n queries; BV needs 1. For a 128-bit secret that is 128 classical queries against one quantum query, at the cost of 2n Hadamards and up to n Z gates.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-10

Design and validate a quantum query workflow for Grover problem.

Answer

What I'd say first (60–120s)

"Before designing anything I need four things pinned down: the search-space size N = 2^n, how many marked items M, whether the predicate arrives as a reversible circuit or as data I have to load, and whether M is known. I'll assume N = 2^n unstructured entries, a unique marked item (M = 1), and an oracle I can implement as a phase-flip circuit. Under those assumptions the design is textbook Grover: prepare the uniform superposition, apply oracle then diffusion k = round(π/(4θ) − 1/2) times, where sin θ = √(M/N), then measure. For n = 4 that's k = 3 and a 96% success probability. The validation is where most candidates stop too early."

Design

Encoding: basis state |x⟩ ↔ candidate x, n qubits. Oracle: a phase oracle U_ω|x⟩ = (−1)^f(x)|x⟩, built as X-gates on the zero bits of the marked pattern, a multi-controlled-Z, then the X-gates undone. Diffusion: H⊗n, X⊗n, multi-controlled-Z, X⊗n, H⊗n. Both multi-controlled-Z gates are the same primitive, so the circuit cost is dominated by them.

Python
from qiskit import QuantumCircuit
from qiskit.circuit.library import MCXGate

n = 4
marked = "1011"          # q3 q2 q1 q0

def phase_oracle(qc, marked):
    for i, b in enumerate(reversed(marked)):   # i=0 -> q0
        if b == "0":
            qc.x(i)
    qc.h(n - 1)
    qc.append(MCXGate(n - 1), list(range(n - 1)) + [n - 1])
    qc.h(n - 1)
    for i, b in enumerate(reversed(marked)):
        if b == "0":
            qc.x(i)

def diffusion(qc):
    qc.h(range(n)); qc.x(range(n))
    qc.h(n - 1)
    qc.append(MCXGate(n - 1), list(range(n - 1)) + [n - 1])
    qc.h(n - 1)
    qc.x(range(n)); qc.h(range(n))

qc = QuantumCircuit(n)
qc.h(range(n))
for _ in range(3):
    phase_oracle(qc, marked)
    diffusion(qc)
qc.measure_all()

Trace (n = 4, N = 16, M = 1, θ = arcsin(1/4) = 14.4775°)

Success probability after k iterations is sin²((2k+1)θ):

k(2k+1)θP(success)
014.48°6.25%
143.43°47.3%
272.39°90.8%
3101.34°96.1%
4130.30°58.2%

k = 3 is optimal; k = 4 over-rotates and drops to 58%.

Validation

  1. Oracle correctness: apply the oracle to each of the 16 basis states and assert the phase is −1 only on |1011⟩. This catches bit-order mistakes, which are the most common bug.
  2. Simulate on Aer with 8192 shots and check the measured distribution against the table above: 96% in 1011 at k = 3.
  3. Post-filter every measured bitstring against the validity constraints; a high rejection rate means the encoding admits infeasible candidates.

Trade-offs

Grover uses O(√(N/M)) oracle calls versus O(N/M) classical queries. That advantage only exists if the oracle is cheap. If the data sits in classical RAM, the oracle must load it, costing O(N) per call, and the speedup vanishes: a classical hash index is O(1) and wins outright. When M is unknown, quantum counting or fixed-point amplitude amplification avoids the over-rotation in the table.

Failure modes

  • Oracle marks the wrong set (wrong X placement): detected by the all-basis-states check above.
  • Over-rotation from a wrong k: detected by comparing measured success probability to sin²((2k+1)θ).
  • Invalid encodings marked: detected by the post-filter rejection rate.
  • Gate error: at 1e-3 two-qubit error and ~110 two-qubit gates, success degrades by 1 − (1−1e-3)^110 ≈ 10%, so 96% ideal becomes ~86% measured. Compare simulator against hardware to isolate it.
  • Verification omitted: always classically check the measured candidate satisfies the predicate; Grover is probabilistic.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Design and validate a quantum query workflow for diffusion.

Answer

What I'd say first. Fix the parameters before touching gates: N = 2^n basis states, M marked, M known, a phase oracle O = I − 2|β⟩⟨β| that flips the sign of the marked subspace, clean ancillas available, and a target success probability of at least 99%. The workflow is six steps: prepare, mark, mix, iterate, measure, verify.

  1. Prepare |s⟩ = H^⊗n|0⟩, the uniform superposition.
  2. Mark with the phase oracle, implemented as compute–classify–uncompute so the workspace returns to |0⟩.
  3. Mix with the diffusion operator D = H^⊗n (2|0⟩⟨0| − I) H^⊗n. The inner operator is a phase flip on every basis state except |0…0⟩: a multi-controlled Z conjugated by X on each qubit.
  4. Iterate k = round((π/4)√(N/M) − 1/2) times.
  5. Measure in the computational basis.
  6. Verify against the closed form below.

Why it works. Write |s⟩ = cos θ|α⟩ + sin θ|β⟩ with sin θ = √(M/N), where |α⟩ is the uniform superposition over non-solutions and |β⟩ over solutions. The oracle reflects about |α⟩; the diffusion operator reflects about |s⟩. Two reflections about lines separated by angle θ compose to a rotation by 2θ. Starting at angle θ from |α⟩, after k iterations the state sits at angle (2k+1)θ, so P(success) = sin²((2k+1)θ). That single formula is the whole validation target.

Worked trace, n = 10, M = 1. N = 1024, sin θ = 1/32, θ = arcsin(1/32) ≈ 0.031255 rad. Optimal k = (π/4)/θ − 1/2 ≈ 24.6, so k = 25.

k(2k+1)θP = sin²
241.53150.9985
251.59400.9995
261.65650.9927

Classical random search needs about 512 oracle calls; this needs 25. The curve peaks at k = 25 and falls off: that is the overshoot you must not ship past.

Validation plan. Simulate the exact statevector for n ≤ 20 (2^20 amplitudes is trivial). Then:

  • Oracle unit test: apply O to each basis state; exactly the M marked states must pick up a −1.
  • Diffusion unit tests: D|s⟩ = |s⟩, D|0…0⟩ = 2|s⟩/√N − |0…0⟩, and D² = I.
  • End-to-end: measured P must match sin²((2k+1)θ) within sampling error at k = 24, 25, 26.
  • Ancilla check: trace out workspace qubits and confirm the reduced state is pure.

Trade-offs. If M is unknown you cannot pick k, and guessing overshoots. Options: quantum counting (Brassard–Høyer–Mosca–Tapp, 1998) to estimate M first; exponential search (Boyer–Brassard–Høyer–Tapp, 1998), which keeps the √(N/M) scaling without knowing M; or fixed-point amplitude amplification (Yoder–Low–Chuang, 2014), which converges monotonically at the cost of a worse constant. If the oracle is expensive, the gate cost of D matters: a multi-controlled Z on n qubits is O(n) Toffoli gates with a clean ancilla and O(n²) without (Barenco et al., 1995).

Failure modes and how you catch them.

  • Oracle sign flipped (bit-flip instead of phase-flip): the state drifts away from |β⟩. Catch it with the per-basis-state oracle test.
  • Diffusion reflecting about zero instead of about the mean: D|s⟩ ≠ |s⟩. Catch it with the D|s⟩ = |s⟩ test.
  • Wrong k: P falls below the k−1 value. Catch it by sweeping k.
  • Ancilla not uncomputed: workspace stays entangled, reduced state is mixed. Catch it with the purity check.
  • Global phase treated as a bug: it is unobservable. Compare measurement distributions, not statevectors.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Design and validate a quantum query workflow for two reflections.

Answer

Core answer (first 90 seconds). "Two reflections" is one Grover iteration. The oracle reflects the state about the axis perpendicular to the marked subspace |β⟩; the diffusion operator reflects about |α⟩, the uniform superposition over non-solutions. Their composition is a rotation by 2θ in the plane spanned by |α⟩ and |β⟩, with sin θ = √(M/N). So the workflow is: fix N and M, build the two-reflection circuit, run k iterations, and validate the measured amplitude against sin((2k+1)θ). Never the probability against that sine.

Assumptions I'd state up front: black-box oracle, M = 1, N = 16 (n = 4 qubits), noiseless statevector simulation, Qiskit 1.x. Under those, θ = arcsin(1/4) = 0.25268 rad.

Design. H on all four qubits, then per iteration: oracle = X on the qubits where the marked bitstring is 0, H on q3, MCX(q0,q1,q2 → q3), H on q3, X back. Diffusion = H, X, MCZ, X, H, with the MCZ built the same way as the MCX. One iteration costs one oracle call, two multi-controlled gates, and O(n) single-qubit gates. A 4-qubit MCX decomposes into O(n) two-qubit gates with n−2 ancillas, O(n²) without: the multi-controlled gate, not the oracle, dominates depth.

Validation. Simulate and compare against the closed form:

Python
# Qiskit 1.x
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
import numpy as np

n, marked = 4, 0b1011          # N = 16, M = 1
theta = np.arcsin(np.sqrt(1 / 2**n))   # 0.25268 rad

def grover(n, marked, k):
    qc = QuantumCircuit(n)
    qc.h(range(n))
    for _ in range(k):
        qc.x([q for q in range(n) if not (marked >> q) & 1])
        qc.h(n - 1); qc.mcx(list(range(n - 1)), n - 1); qc.h(n - 1)
        qc.x([q for q in range(n) if not (marked >> q) & 1])
        qc.h(range(n)); qc.x(range(n))
        qc.h(n - 1); qc.mcx(list(range(n - 1)), n - 1); qc.h(n - 1)
        qc.x(range(n)); qc.h(range(n))
    return qc

for k in range(5):
    sv = Statevector(grover(n, marked, k))
    amp = sv.data[marked]
    print(k, round(amp.real, 4), round(abs(amp) ** 2, 4),
          round(np.sum(np.abs(sv.data) ** 2), 12))

Printed output, with the analytic column alongside:

kamp |1011⟩sin((2k+1)θ)P = amp²Σ|a|²
00.25000.25000.06251.000000000000
10.68750.68750.47271.000000000000
20.95310.95310.90841.000000000000
30.98050.98050.96131.000000000000
40.76270.76270.58171.000000000000

The peak is k = 3, matching round(π/(4θ) − 1/2) = 3. Note k = 2: the amplitude is 0.9531 but the success probability is 0.9084. Reporting the amplitude as the probability is a 4.5-point error.

Trade-offs. Grover uses Θ(√N) oracle calls against Θ(N) classically; for N = 16 that is 3 versus 16 worst case. Don't reach for it when the oracle has exploitable structure (a classical algorithm can beat √N), when N is small enough that the constant factors lose, or when M is unknown: a fixed k then over- or under-rotates, and you need quantum counting or exponential search, which adds a log factor.

Failure modes and how to catch them.

failuredetection
Oracle applies a global phase instead of a relative onemarked amplitude stays flat across k; assert it grows
Over-rotation (k past optimum)plot P against sin²((2k+1)θ); P drops from 0.9613 at k=3 to 0.5817 at k=4
Probability/amplitude confusioncompare |amp|² to sin², not sin
Decoherence during the oraclesuccess probability decays with circuit depth; compare hardware runs to the noiseless sim
Normalization driftassert Σ|a|² = 1 within 1e-12 every iteration

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Design and validate a quantum query workflow for iteration count.

Answer

Core. The iteration count is a derived quantity, not a constant: it comes from the oracle's actual domain size and the number of marked states, and it has to be validated by simulation before you trust it. State the assumptions up front: N is the dimension of the oracle's input register (2^n), M is the number of marked states with 1 ≤ M ≤ N, and the oracle is a phase oracle that flips the sign of marked states. Get any of those wrong and the count is wrong.

Design.

  1. Fix N = 2^n, the register dimension, not the count of valid inputs. If the oracle acts on 2^n states and only K of them are legal, N = 2^n; the illegal states are simply never marked. Using K makes θ too large and k too small.

  2. Get M. If M is known, use it. If not, don't guess 1: run quantum counting (Brassard–Høyer–Tapp: phase estimation on the Grover operator) to estimate M, or switch to fixed-point amplitude amplification (Yoder–Low–Chuang), which needs no M and returns a marked state with probability ≥ 1 − δ in O(√(N/M)) queries.

  3. Compute θ = arcsin(√(M/N)). This is exact; the small-angle shortcut θ ≈ √(M/N) is only safe when M/N ≪ 1.

  4. The success probability after k iterations is p(k) = sin²((2k+1)θ). It peaks where (2k+1)θ ≈ π/2, i.e. k* = π/(4θ) − 1/2. Evaluate both k_floor = ⌊k*⌋ and k_ceil = ⌈k*⌉, pick the larger p(k), and record k with its predicted p. p is not monotonic in k, it oscillates with period π/θ, so overshooting is a real loss, not a rounding detail.

Validate.

  • Statevector-simulate the circuit at k_floor and k_ceil for n up to ~25 qubits, sample many shots, and check the measured success frequency against sin²((2k+1)θ) within shot noise.
  • Sweep k from 0 to 2k* and confirm the empirical argmax is the k you chose.
  • Adversarial oracles: M = 0 (nothing marked) must return the uniform distribution; M = N (everything marked) gives θ = π/2 and k* = 0, so zero iterations.
  • Diffusion check: with no marked state, the diffusion operator must return the uniform superposition unchanged up to global phase. A common bug is reflecting about the mean of the marked subspace instead of all N amplitudes.

Failure modes.

  • Naive rounding of π/4·√(N/M). At N = 4, M = 1: θ = π/6, k* = 1, p(1) = 1.0. The shortcut gives π/4·2 = 1.57 → 2, and p(2) = sin²(5π/6) = 0.25. Overshoot costs 75% of the success probability.
  • M assumed 1 when it isn't: θ is wrong, k is wrong, and the run silently under- or over-rotates.
  • Formula treated as exact for tiny N: at N = 2, M = 1, θ = π/4, k* = 0.5, and p(0) = p(1) = 0.5. Grover buys nothing. The validation sweep catches this.

Artefacts.

Code (Python 3.11):

Python
import math

def grover_plan(N: int, M: int) -> tuple[int, float]:
    # N = oracle register dimension (2**n); M = marked states, 1 <= M <= N
    theta = math.asin(math.sqrt(M / N))
    k_star = math.pi / (4 * theta) - 0.5
    p = lambda k: math.sin((2 * k + 1) * theta) ** 2
    k = max((math.floor(k_star), math.ceil(k_star)), key=p)
    return k, p(k)

Trace for N = 1024, M = 1: θ = arcsin(1/32) = 0.031255 rad; k* = π/(4θ) − 1/2 = 24.629; candidates 24 and 25; p(24) = sin²(49θ) = 0.9985, p(25) = sin²(51θ) = 0.9995 → k = 25.

NMθ (rad)k_floork_ceilp(k_floor)p(k_ceil)chosen
102410.03125524250.99850.999525
1000100.100167780.99530.98277
410.523599111.00001.00001
210.785398010.50000.50000

The first two rows show floor and ceil each winning depending on where k* falls; the last two show the formula's floor at small N.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15

Design and validate a quantum query workflow for overshooting.

Answer

What "overshooting" means here. Grover's iterate is a rotation, not a hill-climb: each iteration rotates the state by a fixed angle 2θ in the two-dimensional plane spanned by the uniform superposition over non-solutions and the uniform superposition over solutions, where sin θ = √(M/N) for M marked items out of N. The success probability after k iterations is P(k) = sin²((2k+1)θ). Because that is a sine squared, it rises, peaks, and then falls: running more iterations than the optimum makes the answer less likely, not more. That fall is the overshoot, and the workflow has to schedule k rather than maximize it.

Assumptions I'd state up front. Unstructured search with a black-box oracle; M marked items; ideal oracle and diffusion; then a separate noisy-hardware pass. If M is unknown, the schedule changes (below).

The optimum. P(k) is maximized when (2k+1)θ ≈ π/2, so

k_opt = round(π/(4θ) − 1/2) ≈ (π/4)√(N/M) oracle queries.

Worked trace, N = 4, M = 1. θ = arcsin(1/2) = 30°. k_opt = round(1.5 − 0.5) = 1.

  • k = 0: uniform, P = sin²(30°) = 0.25.
  • k = 1: oracle flips the marked amplitude to −1/2; diffusion reflects about the mean (−1/8), giving marked amplitude 1 and others 0. P = sin²(90°) = 1.00.
  • k = 2: oracle flips marked to −1; mean is −1/4; reflection gives marked amplitude 0.5 and others −0.5. P = sin²(150°) = 0.25.

One iteration is certain; two iterations drop you back to a coin flip. The same curve for N = 8, M = 1 (θ ≈ 20.7°, k_opt = 2):

k0123
P(k)0.1250.7810.9450.330

Designing the schedule. If M is known, run exactly k_opt and measure. If M is unknown, the usual case, do not guess a large k. Use exponential search (Boyer–Brassard–Høyer–Tapp, Tight bounds on quantum searching, 1998): run Grover with k = 1, 2, 4, 8, … and measure after each block, stopping on the first success. This finds a marked item in O(√(N/M)) queries without knowing M, and the geometric growth means you never sit far past the peak. Quantum counting estimates M first if you need a tighter k.

Validating it. Two passes. (1) Statevector simulation (e.g. Qiskit Aer) for small N: sweep k = 0 … k_opt + 2 and check the measured frequencies against sin²((2k+1)θ); the turnover must appear. (2) Hardware: run each k with a fixed shot count (4096 is a reasonable default) and fit the observed success frequency to the same curve. A curve that peaks at k_opt but sits below the ideal is noise; a curve whose peak is shifted or flattened means your θ is wrong, a bad M or N estimate, not the hardware.

Trade-offs. Fixed-point / oblivious amplitude amplification (Yoder–Low–Chuang, 2014) gives a monotonic success probability with no overshoot, at the cost of a more complex circuit and a constant-factor query increase. Classical repetition of a fixed-k Grover run is simpler but pays the same √(N/M) factor. Pick fixed-point when you cannot afford a failed run; pick exponential search when M is unknown and circuit depth is cheap.

Failure modes and how to catch them.

  • Unbounded loop. Running until success without a cap can overshoot indefinitely. Detect by plotting success frequency against k; the turnover is the signal. Cap k at ceil(π/(4θ_min)) for the smallest M you will assume.
  • Best-of-many post-selection. Running many shots and reporting the most frequent outcome inflates the success rate above what a single run gives. Detect by comparing per-run success rate to the aggregate.
  • Blaming noise alone. If the peak is at k_opt but low, it is noise; if the peak moved, it is a wrong θ. The curve fit separates the two.
  • Monotonic assumption. Treating more iterations as strictly better is the bug the whole workflow exists to prevent; the same curve catches it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Design and validate a quantum query workflow for multiple solutions.

Answer

Assumptions: Unstructured search over N items, M marked solutions, M unknown, M << N. Oracle S_f flips the phase of solution states. Goal: return one solution with high probability.

Design workflow:

  1. Encode: set N = 2^n, build oracle S_f. Validate by applying S_f to all basis states and checking the phase flip lands only on the M solutions.
  2. Estimate M: run quantum counting (Brassard, Høyer, Mosca, Tapp 1998). Phase-estimate the Grover operator G = -H S_0 H S_f. Its eigenvalues are e^{±iθ} with sin²(θ) = M/N. With t ancilla qubits, estimate θ to error ε. Compute M̃ = N sin²(θ̃). If M̃ < 1, declare no solution and stop.
  3. Compute iterations: k = round(π/(4θ̃) - 1/2). Clamp k ≥ 0. If M̃ = N then θ̃ = π/2 and k = 0.
  4. Amplify: apply G k times to the uniform superposition, measure. Verify the output with a classical oracle. If it fails, retry with k ± 1 or fall back to exponential search.
  5. Validate: simulate on small N with known M, compare M̃ and success probability. Then run on hardware with a known solution set and measure the success rate over 1000 shots.

Trade-offs: Counting costs O(√N) queries but yields a deterministic k. Exponential search (Boyer, Brassard, Høyer, Tapp 1998) runs Grover with k = 1, 2, 4, … until success, expected O(√(N/M)) queries, no counting. Fixed-point amplitude amplification (Yoder, Low, Chuang 2014) reaches O(√(N/M)) without knowing M, but needs more qubits and a deeper circuit. Choose counting when N is small or M is large; exponential search when M is very small and simplicity matters; fixed-point when optimal query complexity is required.

Failure modes:

  • M = 0: counting gives θ ≈ 0. Detect via M̃ < 1 and return no solution; otherwise amplitude amplification burns queries for nothing.
  • M = N: every state is marked. k = 0 and measurement returns a solution with probability 1. Ensure the code handles k = 0.
  • Duplicates: the oracle marks duplicates, M is overcounted, k comes out too small, success probability drops. Detect by classical deduplication or by checking the oracle on known inputs.
  • Invalid padding: N not a power of 2, padded with non-solutions. If the oracle marks padding, M is inflated. Detect by verifying the oracle marks only valid solutions.
  • Integer rounding: k must be an integer. Rounding error lowers success probability. Use k = floor(π/(4θ̃) - 1/2) and run multiple trials, or switch to fixed-point.

Worked check: N = 16, M = 3. sin²(θ) = 3/16, so θ = arcsin(√3/4) = 0.4479 rad. k = round(π/(4·0.4479) - 1/2) = round(1.7536 - 0.5) = round(1.2536) = 1. Success probability after one iteration is sin²((2k+1)θ) = sin²(3·0.4479) = sin²(1.3436). Since sin(1.3436) = 0.9743, the probability is 0.9743² = 0.9493. So ~94.9% success, i.e. ~949 successes in 1000 shots. (For contrast, N = 16, M = 4 gives θ = π/6, k = round(1.5 - 0.5) = 1, and sin²(3·π/6) = sin²(π/2) = 1: exact success.)

Validation method:

  • Unit test: N = 16, M = 3, t = 4. Compare M̃ to 3. Run 1000 shots and check the success rate is near 0.949 (accept > 0.9).
  • Oracle test: apply S_f to all 16 basis states and check the phase flip lands on exactly 3.
  • Counting test: for N = 16, M = 3, compare M̃ against the classical count.
  • Hardware test: run on a real device with a known solution set and measure the success rate.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Design and validate a quantum query workflow for zero solutions.

Answer

Core. Assume N = 2^n, an exact oracle f: {0,1}^n → {0,1}, and that f(x) can be evaluated classically. The trap here is that Grover's iteration count k = round(π/4 · √(N/M)) is undefined at M = 0, and running it anyway returns a uniformly random n-bit string: statistically identical to a run that failed to amplify. So the workflow must never infer absence from a search run. Design it as search → verify → count → decide, and validate it by checking that the counting stage's resolution floor sits below M = 1.

Workflow.

stageoperationcostoutput
1 searchGrover, k = ⌊π/4 · √N⌋ iterationsO(√N) oracle callscandidate x
2 verifyclassically evaluate f(x)1 oracle callaccept, or fall through
3 countphase estimation on G with t ancillasO(2^t) Grover iterationsestimate M̃ ± δM
4 decideM̃ < 0.5 → report no solution; else re-search with k = ⌊π/4 · √(N/M̃)⌋—verdict + interval

Why stage 1 cannot certify zero. With M = 0 the oracle is the identity, so the Grover operator G = (2|s⟩⟨s| − I)(I − 2∑_{f(x)=1}|x⟩⟨x|) collapses to 2|s⟩⟨s| − I, and G|s⟩ = |s⟩. The uniform state is a fixed point: every iteration reproduces the same amplitudes, and measurement yields a uniform random string. A non-solution out of stage 1 is evidence about the oracle, not about M.

Counting and the resolution floor. G's eigenvalues are e^{±2iθ} with sin²θ = M/N. Phase estimation with t ancillas returns θ to within π·2^{-t} with probability ≥ 8/π² ≈ 0.81; repeat r times and take the median to drive the failure probability down exponentially in r. Since M = N sin²θ, the error propagates as δM ≈ 2π√(MN)·2^{-t}, so for M = 1, δM ≈ 2π√N·2^{-t}. Choose t so δM < 0.5.

Worked example, n = 20, N = 2^20 = 1,048,576, true M = 0. Stage 1: k = ⌊0.7854 · 1024⌋ = 804 iterations, measure, verify f(x) = 0. Stage 3: need 2^t > 4π√N ≈ 12,900, so t = 14 ancillas, δM ≈ 2π·1024/16,384 ≈ 0.39, at a cost of 2^14 = 16,384 Grover iterations. M̃ comes back inside ±0.39 of zero; the M = 1 case would land at 1 ± 0.39. The floor is 0.5, so the verdict is "no solution" with the interval [0, 0.39).

Trade-offs.

approachqueriescertifies M = 0?notes
Grover search onlyO(√N)nouniform output at M = 0
quantum countingO(2^t) ≈ 16√N hereyes, above the floorneeds t ≈ n/2 ancillas plus a QFT
classical exhaustiveO(N)yes, exactlyright when N ≤ 2^20 or the oracle is cheap

Deciding M = 0 is the OR problem, whose quantum query complexity is Θ(√N) (Bennett–Brassard–Høyer–Mosca–Tapp, 1997), so no workflow beats √N; counting is optimal up to constants, and the classical sweep is the only exact option.

Failure modes and detection.

  • Oracle defect (marks a non-solution): stage 2 rejects the candidate. Detection is the classical check; cost is one oracle call per candidate.
  • Measurement miss called absence: a single non-solution from stage 1 is never reported as absence. Detection: the verdict is gated on stage 3, not stage 1.
  • Infinite retries: an unbounded search-verify loop never terminates at M = 0. Detection: cap stage 1 at k iterations, then escalate to counting.
  • Confidence missing: report M̃ with its interval and the t used, never a bare "no solution".

Validation. Run the pipeline against a synthetic oracle with known M ∈ {0, 1, 2} at n = 20 and confirm the stage-3 interval separates them; then confirm stage 1 alone returns a uniform distribution at M = 0, which is the failure the workflow exists to prevent.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Design and validate a quantum query workflow for unknown solution count.

Answer

Assumptions first. The oracle is a black box U_f: |x⟩|y⟩ → |x⟩|y⊕f(x)⟩ over n qubits, N = 2^n, and M = |{x : f(x)=1}| is unknown and may be zero. I can't assume M is known, and I can't assume the hardware is noiseless. The workflow has to do three things: find a solution when one exists, terminate when none exists, and never report a candidate it hasn't checked.

Why unknown M breaks the naive approach. Grover rotates the state by angle θ where sin²θ = M/N; after k iterations the success probability is sin²((2k+1)θ). The optimal k is (π/4)√(N/M): it depends on M. Guess too low and you under-rotate; too high and you rotate past the solution. With M unknown you can't pick k, and with M = 0 there is no rotation at all, so a fixed-k loop spins forever.

The workflow.

  1. Estimate M with quantum counting (Brassard–Høyer–Mosca): phase-estimate the Grover operator G to recover θ, hence M̂, to constant relative error using O(√(N/M)) applications of G.
  2. If M̂ ≥ 1, run Grover for round((π/4)√(N/M̂)) iterations and measure.
  3. Classically verify the candidate: one evaluation of f(x). Only a verified x is reported.
  4. If verification fails, fall back to BBHT exponential search: run Grover with k = 1, 2, 4, 8, … doubling, each run succeeding with constant probability once k reaches √(N/M). Expected total cost O(√(N/M)) oracle calls, with no prior M.
  5. Cap the search at c√N iterations. Since √(N/M) ≤ √N for any M ≥ 1, hitting the cap means M = 0; declare no solution.
approachneeds M?oracle queriesM = 0
Grover, fixed kyes(π/4)√(N/M)no rotation; loop never ends
Quantum counting, then GrovernoO(√(N/M))M̂ ≈ 0, skip the search
BBHT exponential searchnoexpected O(√(N/M))needs the √N cap to stop

Arithmetic. Take N = 2^20 ≈ 1.05×10^6. With M = 1, k ≈ 0.785×1024 ≈ 804 iterations. With M = 16, k ≈ 0.785×256 ≈ 201. With M = 0, the cap is √N = 1024 iterations, then stop.

Failure modes and detection.

  • Silent no-solution loop: M = 0, exponential search never terminates. Detect with the √N iteration cap; cost is O(√N) wasted oracle calls.
  • Adaptive retries uncounted: re-running with fresh seeds multiplies the true query cost. Detect with a global oracle-call counter; the claimed O(√(N/M)) only holds if every retry is counted.
  • False candidate accepted: measurement noise returns x with f(x) = 0. Detect by classical verification before reporting; cost is one classical call.
  • Expected vs worst-case mixed: BBHT's O(√(N/M)) is expected-case; a single run can be worse. Report both, plus the cap.

Validation. Run on N = 2^10 with planted M ∈ {0, 1, 4, 16}; assert the oracle-call counter matches the predicted order, assert M = 0 terminates at the cap, and inject a bit-flip on the measurement to confirm verification rejects the bad candidate.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Design and validate a quantum query workflow for quadratic boundary.

Answer

Clarify first. "Quadratic boundary" isn't a standard term, so I'd pin it down before designing anything. It's the line between problems where a quantum query algorithm gives at most a quadratic speedup over the best classical algorithm (unstructured search, Grover / amplitude amplification, Θ(√N) queries versus Θ(N)) and problems with exploitable structure where the speedup is exponential (Shor's period finding, Simon's problem). A workflow that validates the quadratic boundary does three things: designs the query algorithm, proves which side of that line the problem sits on, and checks the speedup survives real resource accounting. Assumptions I'd state up front: black-box oracle model, bounded-error (success probability ≥ 2/3), and the classical baseline is the best known algorithm, not a strawman.

Design. Fix the oracle as O|x⟩|0⟩ = |x⟩|f(x)⟩, where f marks the target. The workflow is: (1) count the classical query complexity of the best known algorithm; (2) if it is Θ(N) and the oracle is unstructured, apply amplitude amplification. Grover's iterate (oracle reflection plus diffusion about the mean) run for (π/4)√(N/M) iterations, where M is the number of marked items; (3) if the problem has structure the oracle can exploit, stop. You are not on the quadratic boundary and should look for an exponential algorithm instead.

Validate. Four checks, each with a detection method:

quantity (N = 2^40, M = 1)classicalquantum (Grover)
queries, worst caseN = 1.1×10^12(π/4)√N ≈ 8.2×10^5
queries, averageN/2 ≈ 5.5×10^11same
with k parallel machinesN/k√N: needs k = √N to match

Arithmetic: √(2^40) = 2^20 = 1,048,576; (π/4)·1,048,576 ≈ 823,000 iterations, each one oracle call plus one diffusion step.

  1. Oracle cost omitted. Query count is not gate count. Detect by multiplying T-gates per oracle call by the iteration count. For AES-256 key search the oracle is a full AES circuit (~10^4–10^5 T-gates per call) over 2^256 keys, so ~2^128 iterations is hopeless regardless of the query bound.
  2. Query complexity reported as runtime. Detect with a resource estimate: surface-code cycles per logical gate and magic-state factory throughput turn 8.2×10^5 iterations into wall-clock, which is what the decision actually rests on.
  3. Parallel classical baseline ignored. Detect by comparing against a classical machine with the same budget: √N classical cores match Grover's query count, so if the adversary can rent √N cores the quadratic advantage disappears.
  4. Lower bound applied outside its model. The Ω(√N) bound (Bennett–Bernstein–Brassard–Vazirani, 1997) holds for unstructured search. Detect by confirming the oracle is a random function with no exploitable structure; applying it to a structured problem where Shor gives exponential speedup is simply wrong.

If all four checks pass, the claim is defensible: quadratic in oracle-query complexity, with the oracle cost, runtime, and parallel baseline all accounted for.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Design and validate a quantum query workflow for candidate verification.

Answer

Let me pin down what's being asked, because "quantum query workflow" is doing a lot of work. The candidate space is {0,1}^n, the acceptance test is a classical predicate P, and you only get P as a black-box oracle. The quantum part finds a candidate; verification is the classical re-check of whatever bitstring you measure. So the workflow is amplitude amplification wrapped in a verify-and-retry loop.

Assumptions I'd state before answering: P is unstructured, no exploitable structure, N = 2^20 ≈ 1.05M candidates, exactly one satisfying assignment, and a query model where oracle calls are the counted resource but gates still cost something.

Five steps. Write P as a reference implementation with a test suite. Compile it into an oracle U_P: |x⟩|−⟩ → (−1)^{P(x)}|x⟩|−⟩. Validate U_P against P: the step people skip. Estimate the solution count M, or use an M-free amplification. Run, measure, classically verify the output, retry on failure.

Mechanism. Grover's operator G = (2|ψ⟩⟨ψ| − I)U_P rotates the state by 2θ inside the two-dimensional subspace spanned by the uniform superposition and the marked subspace, with sinθ = √(M/N). After k iterations the success probability is sin²((2k+1)θ).

With N = 2^20 and M = 1: θ = arcsin(1/1024) ≈ 1/1024, k = ⌈(π/4)√(N/M)⌉ = ⌈804.25⌉ = 805, and (2k+1)θ = 1611/1024 = 1.57324 rad, so sin² ≈ 0.999997. 805 oracle calls return the solution with probability 1 − 3×10⁻⁶, against ~524,288 expected classical evaluations: about 650×.

Trade-offs:

approachqueriesneeds M?success
Grover, k = ⌈(π/4)√(N/M)⌉~√Nyes~1
Quantum counting, then Grover~2√Nno~1
Fixed-point AA (Yoder–Low–Chuang 2014)~√Nno≥ 1/2, tunable

Grover is optimal for unstructured search: Θ(√N) queries (Bennett et al. 1997), so nothing beats it without structure. If P is a SAT instance or a graph property, a structured quantum algorithm can beat √N; if P is a hash preimage check, it can't.

Failure modes, with detection. Oracle/verifier divergence: the oracle and the classical verifier implement P differently. Endianness, input width, hash padding. For n ≤ 20, classically simulate U_P and compare the full truth table to P; above that, sample random basis states. This is the same-bug-shared risk: generate the oracle from the same buggy code as the verifier and both agree and both are wrong. Wrong iteration count: if M is larger than assumed you over-rotate past the solution and success collapses. Detect with quantum counting first, or use fixed-point AA. Noise: 805 iterations × ~10^4 gates for a SHA-256 oracle ≈ 8×10^6 gates; at 10⁻³ two-qubit error that's thousands of expected errors, so error-budget the circuit before running. Unmarked measurement: ~3×10⁻⁶ per shot, nonzero. Always classically verify the measured bitstring. Selection bias: report the success rate over many shots, not the best shot.

Cost: query complexity is not wall-clock. Each oracle call is thousands of gates, so the √N query advantage is a gate-count advantage only if the oracle is cheap. Put the oracle's gate cost in the end-to-end budget.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Design and validate a quantum query workflow for oracle ancillas.

Answer

Core answer

Assume the oracle implements f: {0,1}^n → {0,1} as a unitary, ancillas start in |0> unless you deliberately borrow them, and you have a classical reference for f. Design it as compute–copy–uncompute with a phase-kickback target; validate it in two stages, basis states then superpositions, asserting the ancillas return to |0>.

Design:

  • Registers: query q[0..n-1], one target, k ancillas.
  • Compute f into an ancilla, CNOT it onto the target, then run the inverse of the compute circuit so the ancilla returns to |0>.
  • Put the target in |-> = (|0>-|1>)/√2. The CNOT then acts as phase kickback: |x>|-> → (-1)^{f(x)}|x>|->. The target stays in |->, the ancillas stay in |0>, and the query register carries the phase and nothing else.
  • If f is a single Boolean, skip the ancilla entirely and use a phase oracle: cheapest design, no cleanup to validate.
Python
# Qiskit 1.x
qc.ccx(q0, q1, anc)   # compute: anc = q0 AND q1
qc.cx(anc, target)    # copy into target (phase kickback when target=|->)
qc.ccx(q0, q1, anc)   # uncompute: anc back to |0>

Validation:

  • Stage 1, basis states: catches classical logic errors, cheap.
  • Stage 2, superpositions: catches garbage and phase errors.
  • Assert restoration: measure the ancillas and expect all-zero, or check the query register's reduced density matrix is pure.

Why superposition testing is the one that matters

On a basis state |x>, an oracle that leaves garbage |g(x)> in the ancilla still returns the right answer: the query register is definite, so entanglement with the garbage has nothing to destroy. Only in superposition do the garbage branches interfere. Trace f(x0,x1)=x0∧x1 with target |-> and ancilla |0>:

  1. ccx(q0,q1,anc): anc ← x0∧x1. State = ½ Σ |x0 x1>|x0∧x1>|->.
  2. cx(anc,target): target picks up (-1)^{x0∧x1}. State = ½ Σ (-1)^{x0∧x1}|x0 x1>|x0∧x1>|->.
  3. ccx again: anc ← (x0∧x1)⊕(x0∧x1) = 0. State = ½ Σ (-1)^{x0∧x1}|x0 x1>|0>|->.

Ancilla restored, phase applied, query register pure. Drop step 3 and the ancilla stays |x0∧x1>, entangled: the |11> branch decoheres from the other three, and the off-diagonal terms connecting |11> to |00>,|01>,|10> vanish. That is the interference Grover and Deutsch–Jozsa run on.

Trade-offs

  • Coherent uncompute: ~2x the compute depth (compute + inverse), preserves coherence. Default.
  • Reset (measure, re-prepare |0>): shallower, but non-unitary. The ancilla is entangled with the query register, so measuring it projects the query register too and kills the superposition. Use only when the ancilla is provably unentangled.
  • Borrowed ancilla: saves qubits. Valid only if the oracle leaves the ancilla register unchanged for every input, so an unknown |g> survives. Test by feeding a random |g> and checking the output ancilla equals it.

Failure modes

failuresymptomdetection
missing uncomputeancilla entangled, interference lostmeasure ancilla on
basis-only testspasses0>,
garbage phasewrong relative phasecheck oracle is diagonal in the computational basis; global phase is irrelevant
borrowed-ancilla assumption violatedoutput ancilla ≠ inputfeed random
wrong inverse ordernon-unitary or wrong resultcheck U†U = I against a reference
reset instead of uncomputeancilla mixed, query register decoheredcheck purity of the query register's reduced state

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Design and validate a quantum query workflow for data-loading cost.

Answer

Clarify first. "Data-loading cost" only means something once I know whether the data is a lookup table or a predicate. I'd ask: is the oracle a compact circuit (a hash, a comparison) or a table of N arbitrary values? Is it static across queries or reloaded per query? What's N, and how many queries will run? Then I state assumptions: N = 2^30 items, 64 bits each, one marked item, success probability ≥ 2/3, and I charge every logical gate, not just oracle calls.

Core answer. The workflow has four steps, and the query saving is only the last one.

  1. Write the oracle as a circuit, not a black box. If the predicate is arithmetic, "does SHA-256(x) start with 40 zero bits", the oracle is O(poly(b)) Toffoli gates and Grover's √N is real. If the data is an arbitrary table, the oracle is the data: synthesizing it costs O(N) gates.
  2. Choose the data-access path. Compiled oracle: bake the table into a reversible circuit, O(N) gates once, amortized over queries. Bucket-brigade QRAM: O(log N) depth per query but O(N) physical qubits and O(N) gates to build the tree. Classical feed: stream from DRAM.
  3. Charge error correction. Every logical gate becomes roughly 10^3–10^4 physical operations at p ≈ 10^-3; the oracle's gate count, not the iteration count, usually sets the runtime.
  4. Compare against the best classical algorithm on the same data, then find the crossover N.

Arithmetic. N = 2^30, table oracle. Grover needs about 2.6×10^4 iterations. Building the table oracle takes ~10^9 Toffoli gates; at an optimistic 1 µs per logical gate (surface-code logical gates are realistically 10–100× slower), that's ~10^3 s to synthesize. Classical linear scan: 10^9 × 1 ns = 1 s. The quantum path loses by three orders of magnitude. Now make the oracle a hash: 2^128 preimages, oracle ~10^4 gates. Grover needs 2^64 iterations: still infeasible, but the classical 2^128 is worse, and the oracle cost is negligible. The deciding criterion is oracle gate count versus √N × classical-per-item cost.

Trade-offs. Compiled oracle wins when the table is static and queried many times. QRAM wins when the table is large and queried once, but only if a fault-tolerant construction with a published gate count exists: today they're proposals, not hardware. Classical wins whenever the predicate is a lookup and the classical algorithm is sublinear (hash index, B-tree).

Failure modes and detection.

  • Oracle-free analysis: count total logical gates including synthesis; if oracle gates ≥ √N × classical-per-item, there's no speedup.
  • Weakened classical baseline: run the best classical algorithm (indexed lookup, not linear scan) on the same data.
  • Bandwidth ignored: 2^30 × 64 bits = 8 GB; at 20 GB/s DRAM that's 0.4 s of load time, which can exceed the quantum compute. Measure it.
  • Hypothetical memory: require a fault-tolerant QRAM gate count from a primary source; if none exists, mark the design unvalidated.
  • Missing crossover: plot wall-clock versus N for both and report the N where they cross.
stepwhat to chargedetection if skipped
oracleToffoli gates for synthesisoracle gates ≥ √N × classical-per-item
data accessQRAM qubits + tree gates, or DRAM bytesload time vs compute time
error correctionphysical ops per logical gatetotal physical runtime
baselinebest classical algorithmcrossover N reported

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Design and validate a quantum query workflow for transpiled resources.

Answer

Assumptions. I read "quantum query workflow" as a query-based algorithm, Grover or amplitude amplification, where cost is dominated by oracle queries, and "transpiled resources" as what the target actually executes after transpile(). Target: a superconducting device, CX-based basis, fixed coupling map, Qiskit 1.x. On an all-to-all trapped-ion target the routing half of this collapses and only gate count and duration matter.

Core answer. Four stages, each validated on the transpiled circuit rather than the source.

  1. Pin the target: backend name, basis_gates, coupling map, calibration snapshot time, and a fixed seed_transpiler so the layout is reproducible.
  2. Build the logical query circuit, choosing the oracle's multi-controlled gate mode deliberately: it is the biggest single lever on transpiled cost.
  3. Transpile with an explicit optimization_level (the default is 1) and record the pass manager.
  4. Validate the output: logical vs physical qubits, two-qubit gate count, depth, duration, and synthesis error.

Why the multi-controlled gate dominates. An n-controlled X is not native. MCXGate's default noancilla mode decomposes into a CX ladder costing O(n²) CX; v-chain trades n−2 clean ancillas for O(n) CX. The same logical oracle can differ by an order of magnitude in CX count based on a construction-time flag. Ancillas must be uncomputed back to |0⟩, or the oracle is not unitary on the computational register and the interference pattern is wrong.

Worked check. Source: one Toffoli (CCX) on three qubits, basis {cx, u}. After transpile, count_ops() reports cx: 6 plus single-qubit rotations: the standard 6-CX Toffoli decomposition. A report claiming "1 two-qubit gate" counted the source, not the target. The figures in the table are illustrative.

CheckPassFailHow you detect it
Logical vs physical qubitsphysical ≥ logical; extra qubits are ancillas returned to |0⟩ancilla count silently grewcompare num_qubits before/after; statevector-simulate and assert ancillas are |0⟩
Two-qubit gatescount from count_ops() on the transpiled circuitopaque gate counted as onescan circuit.data for ops with definition is None that are not in basis_gates
Connectivityevery 2q gate's qubits are an edge in the coupling maprouting ignoredcheck each 2q gate against backend.coupling_map
Durationscheduled circuit duration from the target's instruction durationssource depth advertisedschedule with scheduling_method and read circuit.duration
Calibrationsnapshot timestamp newer than the job's expected queue timestale calibrationcompare snapshot time to now; re-transpile if older

Trade-offs. optimization_level 0 compiles fastest and stays closest to source; 3 spends more compile time for lower depth. Ancilla mode: pick v-chain when clean qubits are spare and CX error dominates; pick noancilla when qubit count is the binding constraint. Routing: SabreSwap is the default and usually wins on depth; StochasticSwap is the fallback. If any block is synthesized from an arbitrary unitary, record the synthesis error the pass reports: an approximation that is fine on a simulator can be the dominant error on hardware.

Failure modes. The table's Fail column is the operational cost: an opaque gate counted as one under-reports the job's real gate count, so a budget check passes and the job then runs long or is rejected; a stale calibration means the layout was chosen for a coupling map and error rates that no longer hold, so the depth you validated is not the depth you get. Both are caught before submission by the checks above, not after.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Design and validate a quantum query workflow for shot evaluation.

Answer

Assumptions first. "Shot evaluation" here means deciding whether a shot-based result from a query circuit is trustworthy. I'll fix a concrete case: 3 qubits, one Grover iteration on a single marked state, 4096 shots per configuration, superconducting hardware with 1.5% symmetric readout error per qubit. If your setup differs, the workflow holds and only the numbers move.

The workflow, five steps.

  1. Freeze the reference. Statevector-simulate the circuit with no shots. For 3 qubits and one Grover iteration, sin θ = 1/√8, so the marked state has amplitude sin(3θ) = 0.8839 and probability 0.78125; each of the other seven states gets 0.03125. That exact vector is the target: never a second shot run.

  2. Size the shot budget from the resolution you need. For a probability from N shots, SE = √(p(1−p)/N). At p = 0.78125, N = 4096 gives SE = 0.0065, a 95% CI of ±1.3 points. For ±0.5 points you need N ≈ 26,000. Write the number down before running.

  3. Run four configurations, not one: ideal (statevector sampling), noisy simulator (device noise model from a dated calibration snapshot), raw hardware, and hardware with readout mitigation. Run the noisy simulator twice (full model, then gate noise only) so the gap between them isolates readout error from gate error.

  4. Score with one end-to-end metric. Total variation distance, TVD = ½ Σ|p_ideal − p_measured|. With 1.5% symmetric readout error the marked state's observed probability drops to ≈0.748 and the three one-bit-away states rise to ≈0.042 each, giving TVD ≈ 0.033. The shot-noise floor at N = 4096 is ≈0.010, so raw hardware sits 3× above noise: the readout error is real, not sampling.

configurationexpected TVD vs idealwhat it isolates
ideal, sampled at 4096 shots≈0.010sampling floor
noisy simulator, gate noise only≈0.012 (illustrative)gate error
noisy simulator, full model≈0.033gate + readout
raw hardware≈0.033gate + readout + drift
mitigated hardware≈0.011residual after readout correction
  1. Validate, don't just report. Three checks catch the common production misses:
  • Bit order. Apply X to qubit 0 only and measure. Qiskit is little-endian, so the rightmost character must be set ("001" on 3 qubits). Seeing "100" means the whole distribution is mirrored.
  • Shot accounting. Assert Σ counts == submitted shots. A job returning 4090 of 4096 silently changes your denominator.
  • Run count. Pre-register K runs and report the median, not the best. The minimum of 10 runs sits about 1.5 standard errors below the mean; with SE 0.005 that is 0.008 of bias: the same size as the entire mitigation gain.

Trade-offs. Readout mitigation by assignment-matrix inversion is cheap, but the matrix is a tensor product of [[1−e, e],[e, 1−e]], so its condition number is (1−2e)⁻³. At e = 0.015 that is 1.10 and variance inflates by at most cond² ≈ 1.2, taking SE from 0.0065 to 0.0071: acceptable. At e = 0.15 it is 2.9 and inversion starts emitting negative probabilities; switch to M3 or cut qubits. Mitigation fixes measurement error only: if TVD stays high after mitigation, the residual is gate error and you need ZNE or a better transpile, not a better calibration matrix.

Failure modes and how you see them. Mitigation-only reporting: if mitigated TVD falls below the 0.010 shot-noise floor, the mitigation is fitting the calibration, not the circuit. Dropped shots: alert when Σ counts < 99.9% of submitted. Cherry-picked winner: a reported TVD that is the minimum of many runs is biased low by ~1.5 SE. Bit-order error: the X-on-q0 check above.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Design and validate a quantum query workflow for reproducible query claims.

Answer

What a strong candidate says first. A reproducible query claim has four pinned parts: the promise on the input, the oracle access model, the cost accounting, and the statistical evidence. Leave any of them implicit and you have a number from one run, not a claim.

Concrete example: "Grover search finds the unique marked item among N = 2^20 with 804 oracle calls, versus 524,288 classical queries on average." The promise is exactly one marked item. The access model is a phase oracle O|x⟩ = (−1)^{f(x)}|x⟩, one call per query. The cost accounting is oracle calls. The evidence is a success probability with a confidence interval. That claim is falsifiable; "quantum gives a speedup" is not.

The workflow. Six stages, each producing an artifact the next stage consumes and a reviewer can re-run.

stageartifactfalsification check
freeze promisepromise statement + instance generator + seedclassical enumeration for n ≤ 20
fix access modeloracle circuit + definition of "one query"count oracle calls in the compiled circuit
estimate resourcesT-count, T-depth, qubit count from a resource estimatorinclude the oracle; compare to classical cost
compileQIR or QASM3 + transpiler target + seedre-transpile, diff the output
executeshot counts + backend + calibration timestamperror bars; flag simulator-only runs
compareclassical baseline on the same instancessame cost model, same instance distribution
archiveall of the above + git SHAre-run from archive reproduces the claim

Why each stage matters. The promise is not decoration. Grover's 804 iterations is optimal only when exactly one item is marked. With zero marked items the final state is uniform and the success probability is 0; with two, the rotation angle doubles and 804 iterations overshoots, so the success probability oscillates rather than converging. Detect it before the quantum run:

Python
# Python 3.11 — classical promise check, run before any quantum job
def check_promise(f, n):
    marked = [x for x in range(1 << n) if f(x)]
    if len(marked) != 1:
        raise ValueError(f"promise violated: {len(marked)} marked items")
    return marked[0]

The access model changes the cost. A phase oracle costs one query; a bit oracle O|x⟩|y⟩ = |x⟩|y ⊕ f(x)⟩ costs one query plus an ancilla and a CNOT-equivalent, and converting it to a phase oracle costs one more query and an ancilla in |−⟩. Same algorithm, different T-count. If the claim is asymptotic query complexity, count oracle calls; if it is practical speedup, count T-gates and wall clock, and say which.

Trade-offs. Fixed-iteration Grover (⌊π/4 √N⌋ = 804 for N = 2^20) is optimal when the promise holds and simpler to compile. Boyer–Brassard–Høyer–Tapp exponential search costs a constant factor more, roughly 1/√k scaling when k items are marked, but survives an unknown k. Choose fixed when the problem guarantees uniqueness; choose BBHT when it does not. Simulator runs give exact amplitudes and no shot noise; hardware runs give the only evidence that survives noise. A claim validated only on a simulator is a simulator-only claim, and it should be labelled as such. At 804 iterations the success probability is 1 − O(1/N), so a single run is not evidence: you need shot counts and a confidence interval.

Failure modes and how they are detected. Promise violation: classical enumeration on small n, or amplitude estimation on the real instance; cost is a wrong answer with probability near 1. Cost laundering: a resource estimator that includes the oracle, not just the query count; cost is an inflated speedup. Simulator-only claim: require at least one hardware run with error bars. Classical comparator mismatch: run the baseline on the same instance distribution and cost model. Hidden retries: instrument the oracle call counter, including calls inside repeat-until-success loops; cost is an undercounted query complexity.

The archive is the deliverable. Every artifact in the table above, plus the git SHA, goes into one directory. A reviewer re-runs from that directory and either reproduces the claim or finds the stage where it breaks. That is what makes the claim reproducible rather than anecdotal.

Curated: · Written: · Reviewed:

Difficulty: Hard