Skip to content
Tech Interview Prep
Technical interview guide

Quantum Gates & the Circuit Model

How quantum programs are expressed as circuits of unitary gates acting on qubits: the single- and multi-qubit gates every quantum algorithm is built from.

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

Scope: IBM Quantum and Qiskit current circuit/transpiler documentation; OpenQASM 3; QIR specification 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-2

How does gate application order in mathematical matrix composition correspond to temporal execution order in a quantum circuit diagram?

Answer

In quantum circuit diagrams, physical time advances strictly from left to right. When gate $A$ is placed before gate $B$ on the same qubit wire, $A$ executes first at $t_1$, followed by $B$ at $t_2$. In linear algebra, operations act on state vectors by matrix-vector multiplication: $|\psi'\rangle = U |\psi\rangle$. Because operators act on the ket directly to their right, successive application of $A$ followed by $B$ maps $|\psi\rangle \to B(A|\psi\rangle) = (BA)|\psi\rangle$. Thus, temporal left-to-right sequencing in a circuit diagram corresponds directly to right-to-left operator composition in matrix algebra: $U_{\text{total}} = U_n U_{n-1} \dots U_1$.

A second orthogonal ordering rule governs multi-qubit systems: tensor product spatial ordering. In standard textbook notation, qubit 0 is the most significant index (leftmost in the Kronecker product $q_0 \otimes q_1$). In Qiskit, qubit 0 is the least significant index (rightmost: $q_1 \otimes q_0$, Little Endian). When composing gates in parallel across multiple wires, $(A \otimes B)$ maps to wire spatial placement according to the endianness convention adopted by the runtime framework.

Worked Example: Non-Commuting 1-Qubit Sequence

Consider applying a Hadamard gate $H$ followed by a Pauli $X$ gate on wire $q_0$:

Circuit diagram (Time flows left to right):
     t=1       t=2
q_0: ──[ H ]────[ X ]──
  1. Mathematical composition acting on input $|0\rangle$: $$U_{\text{total}} = X \cdot H$$

  2. Matrix evaluation: $$H = \frac{1}{\sqrt{2}}\begin{pmatrix} 1 & 1 \ 1 & -1 \end{pmatrix}, \quad X = \begin{pmatrix} 0 & 1 \ 1 & 0 \end{pmatrix}$$ $$U_{\text{total}} = \begin{pmatrix} 0 & 1 \ 1 & 0 \end{pmatrix} \frac{1}{\sqrt{2}}\begin{pmatrix} 1 & 1 \ 1 & -1 \end{pmatrix} = \frac{1}{\sqrt{2}}\begin{pmatrix} 1 & -1 \ 1 & 1 \end{pmatrix}$$

If evaluated incorrectly as left-to-right matrix multiplication ($H \cdot X$): $$H \cdot X = \frac{1}{\sqrt{2}}\begin{pmatrix} 1 & 1 \ 1 & -1 \end{pmatrix} \begin{pmatrix} 0 & 1 \ 1 & 0 \end{pmatrix} = \frac{1}{\sqrt{2}}\begin{pmatrix} 1 & 1 \ -1 & 1 \end{pmatrix} \neq X \cdot H$$ Applying $X H |0\rangle$ yields $|+\rangle = \frac{|0\rangle + |1\rangle}{\sqrt{2}}$, whereas $H X |0\rangle = H |1\rangle = |-\rangle = \frac{|0\rangle - |1\rangle}{\sqrt{2}}$, which differs by an observable relative phase.

Comparison Table: Circuit vs Matrix Formalism

Representation DimensionCircuit Diagram ConventionMatrix Algebraic RepresentationCommon Failure Mode
Time DimensionLeft-to-right horizontal axes ($t_1 \to t_2$)Right-to-left composition ($U_2 U_1$)Multiplying matrices in script read order ($U_1 U_2$)
Space / Wire DimensionTop-to-bottom qubit wires ($q_0, q_1, \dots$)Kronecker product order ($q_n \otimes \dots \otimes q_0$ in Qiskit)Inverting target/control or endianness transposition
Parallel OperationsVertical alignment at same time sliceTensor product ($A \otimes B$)Treating parallel independent gates as sequential terms

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-1

Why must all quantum logic gates in the standard circuit model be represented by unitary operators, and what physical principle does this enforce?

Answer

A gate in the circuit model is one time step of a system you are not measuring, and an unmeasured system evolves by the Schrödinger equation. With a Hermitian Hamiltonian $H$, the propagator over time $t$ is $U = \exp(-iHt/\hbar)$; exponentiating an anti-Hermitian operator gives a unitary one. Unitarity is therefore not an extra axiom imposed on gates: it is what closed-system evolution looks like. The physical principle it enforces is conservation of probability: $\langle\psi|\psi\rangle$ is invariant under $U$, so the squared amplitudes of a state still sum to 1 after the gate. The same algebra gives the second consequence, reversibility: $U^\dagger = U^{-1}$, so every gate has an inverse and no information is destroyed. Measurement and noise sit outside the gate set: measurement is nonlinear on the state vector, and noise is non-invertible and only defined on density matrices.

Why Hermitian $H$ gives unitary $U$. Write $U(t) = \exp(-iHt/\hbar)$. Then $U^\dagger = \exp(+iH^\dagger t/\hbar) = \exp(+iHt/\hbar) = U^{-1}$, using $H = H^\dagger$. Conversely, every finite-dimensional unitary has the form $\exp(-iH)$ for some Hermitian $H$ (diagonalise $U$, take the log of its phases), so "unitary" and "closed-system evolution" pick out the same set of operators.

Norm preservation, with numbers. For any $|\psi\rangle$, $\langle\psi'|\psi'\rangle = \langle\psi|U^\dagger U|\psi\rangle$. Requiring this to equal $\langle\psi|\psi\rangle$ for every state forces $U^\dagger U = I$. Take $M = \mathrm{diag}(1, 0.5)$ and $|+\rangle = (|0\rangle+|1\rangle)/\sqrt{2}$. Then $M|+\rangle = (|0\rangle + 0.5|1\rangle)/\sqrt{2}$, whose norm squared is $(1 + 0.25)/2 = 0.625$. Measuring in the computational basis gives outcome probabilities $0.5$ and $0.125$: they sum to $0.625$, not 1. Probability has leaked out of the register, which is exactly what a non-unitary "gate" would do.

That matrix is not a straw man. It is the no-jump Kraus operator $E_0$ of the amplitude-damping channel at rate $\gamma = 0.75$, since $\sqrt{1-\gamma} = 0.5$. Alone it loses norm; the channel is trace-preserving only once the jump operator $E_1 = \sqrt{\gamma},|0\rangle\langle 1|$ is added, so that $E_0^\dagger E_0 + E_1^\dagger E_1 = I$. Applied to $|+\rangle$, the pair gives $P(0) = 0.875$ and $P(1) = 0.125$, which sum to 1.

Reversibility. Inner products are preserved: $\langle\phi'|\psi'\rangle = \langle\phi|U^\dagger U|\psi\rangle = \langle\phi|\psi\rangle$, so orthogonal inputs stay orthogonal and no two distinct inputs ever collide. The map is injective, hence invertible on the register. This is why the circuit model cannot implement a classical AND on two qubits without keeping the inputs: the reversible version is Toffoli, which carries the inputs through. It is also why cloning fails: $|\psi\rangle \mapsto |\psi\rangle|\psi\rangle$ is nonlinear, so no unitary does it.

Where unitarity stops. Measurement is a projection followed by renormalisation, and it is irreversible. Decoherence is a coupling to an environment you do not track. Both are modelled as completely positive trace-preserving maps $\rho \mapsto \sum_k E_k \rho E_k^\dagger$ with $\sum_k E_k^\dagger E_k = I$: trace-preserving, but not norm-preserving on a state vector. Stinespring dilation says any such channel on a system is a unitary on system-plus-ancilla with the ancilla discarded, which is the precise sense in which unitarity is still the underlying dynamics.

Python
import numpy as np

def is_unitary_gate(matrix: np.ndarray, atol: float = 1e-10) -> bool:
    if matrix.ndim != 2 or matrix.shape[0] != matrix.shape[1]:
        return False
    n = matrix.shape[0]
    if n == 0 or (n & (n - 1)) != 0:   # a gate on n qubits is 2^n x 2^n
        return False
    u_dagger_u = matrix.conj().T @ matrix
    # rtol=0 so atol is the real tolerance; numpy's default rtol=1e-5 would
    # silently loosen this check to ~1e-5 on identity entries.
    return np.allclose(u_dagger_u, np.eye(n, dtype=matrix.dtype), atol=atol, rtol=0.0)

H = np.array([[1, 1], [1, -1]], dtype=complex) / np.sqrt(2)
assert is_unitary_gate(H)                                  # H^dagger H = I
assert not is_unitary_gate(np.diag([1.0, 0.5]).astype(complex))  # diag(1, 0.25) != I
Unitary gate $U$Measurement $P_m$Noise channel $\mathcal{E}$
Map$|\psi\rangle \mapsto U|\psi\rangle$$|\psi\rangle \mapsto P_m|\psi\rangle / \sqrt{\langle\psi|P_m|\psi\rangle}$$\rho \mapsto \sum_k E_k \rho E_k^\dagger$
Norm / trace$|U|\psi\rangle| = ||\psi\rangle|$projection, renormalised by outcome probabilitytrace-preserving: $\sum_k E_k^\dagger E_k = I$
Reversibleyes, $U^{-1} = U^\dagger$no, state collapsesno, information leaks to the bath
Settingclosed systemcoupling to a classical apparatusopen system

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

Design and validate a circuit workflow for gate order.

Answer

Assumption: "gate order" means the compiler's freedom to reorder gates inside a circuit, and "validate" means proving the reordered circuit is semantically equivalent to the one that went in.

Core answer. A gate-order workflow is a compiler pipeline with a proof obligation bolted to the end. Five stages: canonicalize (decompose to the target basis and unroll, so every gate has a known matrix), build the DAG over qubit wires, run commutation analysis on adjacent pairs, reorder to expose cancellations and re-synthesize, then validate the result against the pre-optimization circuit. Stage 3 is where the bugs live; stage 5 is the gate that catches them.

Why the rule is keyed on qubit role, not gate name. CNOT is |0⟩⟨0|⊗I + |1⟩⟨1|⊗X. A Z on the control commutes with it; an X on the control does not. Trace both on |10⟩:

  • Z then CNOT: Z|10⟩ = −|10⟩, CNOT → −|11⟩.
  • CNOT then Z: CNOT|10⟩ = |11⟩, Z on q0 → −|11⟩. Same.
  • X then CNOT: X|10⟩ = |00⟩, CNOT → |00⟩.
  • CNOT then X: CNOT|10⟩ = |11⟩, X on q0 → |01⟩. Different.

So the commutation table must be indexed by (gate, which qubit it touches), not by gate name. Qiskit encodes this in the CommutationAnalysis and CommutationTransformation transpiler passes; Cirq exposes cirq.commutes(a, b, default=False); pytket's CommuteThroughMultis does the same job.

Validation: pick the cheapest check that is still exact.

checkcostcatchesmisses
rule tableO(1) per pairknown pairsanything not in the table
matrix commutation2^k × 2^k multiply, k = qubits touchedexact for that pairnothing local
Operator.equiv on the full circuit2^n × 2^n denseeverything, up to global phaseglobal phase
randomized statevectorO(2^n) per shotmost reorder bugsrare phase errors

Use the rule table in the inner loop, fall back to the matrix check, and run Operator.equiv once at the end. Above roughly 12 qubits the dense check is out of reach: a 2^12 × 2^12 complex matrix is 16,777,216 entries, about 268 MB at 16 bytes each, so switch to randomized statevector comparison plus structural DAG equality.

Failure modes to test for. Invalid cancellation: T·T is not identity, T·T† is, so a rule that treats "same gate twice" as identity is wrong. Overlapping controls: moving a gate past a controlled gate when it touches the control qubit, exactly the X-on-control case above. Symbolic parameters: a gate carrying a Parameter has no numeric matrix until bound, so a matrix check must either bind it to sample values (and then the rule is only verified at those points) or reason symbolically; a rule table keyed on angle equality is fragile because ParameterExpression equality is structural, not numeric. Global versus relative phase: Operator.equiv ignores global phase, which is fine until the block is used as a controlled gate, then that global phase becomes relative and changes the result. Hardware timing: reordering across a barrier or a delay is a bug, and on hardware the pulse schedule shifts as well.

Trade-off. Aggressive reordering (optimization level 3 versus 1) buys circuit depth at the cost of compile time and a larger surface for every failure mode above. If the circuit is small enough for a dense equivalence check, take the aggressive reordering and let the check be the gate. If it is not, restrict reordering to pairs in the rule table and validate structurally.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

What are the matrix representations, eigenbases, and physical actions of the Pauli X, Y, and Z gates on single-qubit states on the Bloch sphere?

Answer

In an interview I'd start by fixing conventions: computational basis |0>=(1,0)^T, |1>=(0,1)^T, and I'll quote gates up to global phase because that phase is unobservable. Then the direct answer: X, Y, Z are the three Pauli matrices. Each is Hermitian, unitary, traceless, squares to I, and any two anticommute. On the Bloch sphere each is a pi rotation about its named axis.

Matrices: X = [[0,1],[1,0]], Y = [[0,-i],[i,0]], Z = [[1,0],[0,-1]].

Eigenbases: X: |+>=(|0>+|1>)/sqrt(2) with +1; |->=(|0>-|1>)/sqrt(2) with -1. Z: |0> with +1; |1> with -1. Y: |+i>=(|0>+i|1>)/sqrt(2) with +1; |-i>=(|0>-i|1>)/sqrt(2) with -1.

To see the physical action, take |psi>=alpha|0>+beta|1> with Bloch vector r=(2Re(alpha* beta), 2Im(alpha* beta), |alpha|^2-|beta|^2). X sends alpha|0>+beta|1> to alpha|1>+beta|0>, so r -> (r_x, -r_y, -r_z). It flips the bit and rotates the Bloch vector about the x-axis by pi. Z sends it to alpha|0> - beta|1>, so r -> (-r_x, -r_y, r_z). It flips the relative phase and rotates about z. Y sends it to -i beta|0> + i alpha|1>, so r -> (-r_x, r_y, -r_z). It does both bit and phase flip.

The rotation forms: R_x(pi)=e^{-i pi X/2}=-iX, R_y(pi)=e^{-i pi Y/2}=-iY, R_z(pi)=e^{-i pi Z/2}=-iZ. The -i is the global phase I said I'd drop.

Now the failure modes and operational cost. On superconducting transmons, X and Y are microwave pulses, typically 20-40 ns. Z is often virtual: a phase shift of the frame, zero time, zero gate error in the ideal. That asymmetry matters in compilers: Z rotations are pushed into frame changes, X/Y cost time and error.

What breaks:

  • Decoherence. T1 amplitude damping and T2 dephasing act during the 20-40 ns pulse. Detection: T1/T2 experiments and randomized benchmarking, which gives error per gate.
  • Calibration drift. Pulse amplitude or phase drifts turn X into R_x(pi+epsilon), leaving a residual z component. Detection: tomography or RB; repeated X X should return identity, but over-rotation shows up as population leakage or phase error.
  • Crosstalk. A pulse on one qubit drives neighbors. Detection: simultaneous RB and crosstalk characterization.
  • Virtual-Z limits. Virtual-Z is exact only for a rotation about the physical z-axis. If you need a rotation about an axis in the xy plane, or if the frame reference has drifted, a frame change alone is not enough; you conjugate with X/Y pulses and pay the pulse time and error again. If you measure immediately after a virtual-Z, populations are unchanged, so the phase must be absorbed into the measurement basis or the next pulse.

The engineering is about which rotations are free and which cost coherence.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

How does the Hadamard gate create equal superposition, and what is its geometric representation on the Bloch sphere?

Answer

Core answer (say this first). Assume one qubit in the computational basis ${|0\rangle,|1\rangle}$ and the standard Hadamard $H = \frac{1}{\sqrt{2}}\begin{pmatrix}1&1\1&-1\end{pmatrix}$. It sends $|0\rangle \mapsto |+\rangle = \frac{1}{\sqrt{2}}(|0\rangle+|1\rangle)$ and $|1\rangle \mapsto |-\rangle = \frac{1}{\sqrt{2}}(|0\rangle-|1\rangle)$: equal magnitudes, relative phase $0$ versus $\pi$. Geometrically it is a $\pi$ rotation about the axis $\vec{n} = \frac{1}{\sqrt{2}}(\hat{x}+\hat{z})$: the diagonal in the $XZ$ plane. That rotation swaps the $X$ and $Z$ axes and flips $Y$, so $H$ maps the $Z$ basis onto the $X$ basis.

Why it is that rotation. $H = (X+Z)/\sqrt{2}$. A rotation about $\vec{n}$ by $\theta$ is $R_{\vec{n}}(\theta) = \exp(-i\tfrac{\theta}{2},\vec{n}\cdot\vec{\sigma})$. At $\theta=\pi$ this collapses to $R_{\vec{n}}(\pi) = -i,(\vec{n}\cdot\vec{\sigma}) = -i,(X+Z)/\sqrt{2} = -iH$. The factor $-i$ is a global phase and is unobservable, so $H$ is a $\pi$ rotation about the diagonal axis.

InputBloch vectorAfter $H$Output
$|0\rangle$$(0,0,1)$$x\leftrightarrow z$$(1,0,0)=|+\rangle$
$|1\rangle$$(0,0,-1)$$x\leftrightarrow z$$(-1,0,0)=|-\rangle$
$|+\rangle$$(1,0,0)$$x\leftrightarrow z$$(0,0,1)=|0\rangle$
$|+i\rangle$$(0,1,0)$$y\to -y$$(0,-1,0)=|-i\rangle$

This is exactly $HZH = X$, $HXH = Z$, $HYH = -Y$.

Alternatives, and when to pick each.

  • Full $H$ as a basis change. The three-pulse sequence $R_z(\pi/2),R_x(\pi/2),R_z(\pi/2) = -iH$ is exact. On current superconducting transmon devices the $R_z$'s are typically virtual phase offsets (no pulse, ~0 ns) and only the $R_x(\pi/2)$ is a calibrated DRAG pulse, commonly tens of nanoseconds (~20–40 ns). Use this when you need $H$'s self-inverse, $X\leftrightarrow Z$-swapping action.
  • Two pulses. $R_z(\pi)$ then $R_y(\pi/2)$ also equals $-iH$: one fewer pulse, but it needs a calibrated $R_y$.
  • State prep only. If all you need is $|+\rangle$ from $|0\rangle$, a single $R_y(\pi/2)$ gives it. But $R_y(\pi/2) = HZ$, not $H$: it sends $|1\rangle \mapsto -|-\rangle$, so it is not self-inverse and will not map the $X$ basis back to $Z$.

The deciding criterion is whether you need the full self-inverse basis change (use $H$ or its $R_z$–$R_x$–$R_z$ decomposition) or just one state (use the cheapest native $\pi/2$ rotation), and which rotations your device actually calibrates.

Failure modes.

  • Confusing $|+\rangle$ with the maximally mixed state $\tfrac{1}{2}I$. Both give 50/50 counts in a $Z$-basis readout. They differ in purity: $\mathrm{Tr}(\rho^2)=1$ for $|+\rangle$, $0.5$ for $\tfrac{1}{2}I$. Detect it by applying $H$ again: $H|+\rangle = |0\rangle$ with probability 1, while $H(\tfrac{1}{2}I)H = \tfrac{1}{2}I$ still reads 50/50, or by measuring in the $X$ basis, where $|+\rangle$ gives $+1$ with certainty and $\tfrac{1}{2}I$ gives 50/50.
  • Dropping the relative phase. Preparing $|+\rangle$ with $R_y(\pi/2)$ and then treating it as $H$ puts the wrong sign on the $|1\rangle$ branch, so interference terms cancel. Detect it with a Ramsey-type fringe: contrast falls from 1 toward 0.
  • Decoherence. $T_2$ bounds how long the coherence survives; the equal-magnitude populations are robust, the phase is not.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

Design and validate a circuit workflow for Hadamard.

Answer

Core answer. A Hadamard validation workflow has three tiers, and you should name which tier you're in before you start. Assume the gate is a single-qubit unitary, the simulator is exact, and hardware carries readout and gate error. Tier 1 is algebraic: check the 2×2 matrix against its defining properties. Tier 2 is state-vector: drive the four basis states through and compare amplitudes. Tier 3 is compositional: run sequences where H's cancel or conjugate other gates, because that is where real bugs live. On hardware, add a fourth tier, randomized benchmarking or process tomography, because state-vector comparison alone cannot separate a coherent phase error from a stochastic one.

The object under test.

H = (1/√2) · [[1, 1], [1, −1]]

Two properties define it: H² = I (self-inverse), and H X H = Z, H Z H = X (it swaps the X and Z bases). The 1/√2 is not decoration: it is what keeps the state normalized, and it is the single most common omission.

Tiers 1 and 2, as code.

Python
import numpy as np
H = np.array([[1, 1], [1, -1]]) / np.sqrt(2)
X = np.array([[0, 1], [1, 0]])
Z = np.array([[1, 0], [0, -1]])
assert np.allclose(H @ H, np.eye(2))                          # self-inverse
assert np.allclose(H @ X @ H, Z)                              # basis swap
assert np.allclose(H @ Z @ H, X)
assert np.allclose(H @ [1, 0], [1/np.sqrt(2),  1/np.sqrt(2)]) # H|0> = |+>
assert np.allclose(H @ [0, 1], [1/np.sqrt(2), -1/np.sqrt(2)]) # H|1> = |->

Tier 3: the interference trace. This is the test that catches phase bugs. Start in |0⟩, apply H, apply Z, apply H:

|0⟩ = [1, 0] H|0⟩ = [1/√2, 1/√2] = |+⟩ Z|+⟩ = [1/√2, −1/√2] = |−⟩ H|−⟩ = [0, 1] = |1⟩

The Z gate flipped the relative sign; the final H turned that sign into a deterministic bit flip. Measure in the Z basis and you get 1 with probability 1. If your implementation drops the sign on |1⟩, this test returns |0⟩ instead: a failure the H² = I check passes cleanly.

Failure modes and how each is detected.

failuresymptomdetection
1/√2 omittedstate norm = √2⟨ψ
sign on |1⟩ droppedH|1⟩ = |+⟩ not |−⟩H·Z·H test returns |0⟩
H treated as randomizerno coherenceoff-diagonal ρ = 0; X-basis measurement random
H's cancelled across intervening gateswrong unitarycompare optimized vs unoptimized state vectors

Trade-offs. Matrix comparison is exact and free but only tests the ideal gate. Randomized benchmarking gives a single error rate and is robust to state-prep error, but it is blind to coherent errors: a systematic phase error can average out. Process tomography recovers the full channel but needs O(4ⁿ) measurement settings, so it is practical only for one or two qubits. Pick by what you are debugging: algebraic bug → tier 1; composition bug → tier 3; hardware drift → RB; coherent error → tomography.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

How do the Pauli-Z, S, and T gates relate algebraically, and why is the T gate specifically the bottleneck in fault-tolerant gate synthesis?

Answer

Algebraic relation

$Z$, $S$, and $T$ are all diagonal phase gates: rotations about the Z axis:

$$Z = \begin{pmatrix}1&0\0&-1\end{pmatrix} = \mathrm{diag}(1, e^{i\pi}), \qquad S = \mathrm{diag}(1, e^{i\pi/2}), \qquad T = \mathrm{diag}(1, e^{i\pi/4})$$

Each is exactly the square root of the one above it: no global phase is needed:

$$T^2 = \mathrm{diag}(1, e^{i\pi/2}) = S, \qquad S^2 = \mathrm{diag}(1, e^{i\pi}) = Z, \qquad T^4 = Z.$$

Equivalently $S = Z^{1/2}$ and $T = Z^{1/4}$. All three fix $|0\rangle$ and multiply $|1\rangle$ by $e^{i\pi/4}$, $e^{i\pi/2}$, $e^{i\pi}$ respectively.

Where the Clifford boundary falls

The Clifford group is the normalizer of the Pauli group, $\mathcal{C} = {U : U\mathcal{P}U^\dagger \subseteq \mathcal{P}}$. $Z$ is Pauli, so it is Clifford. $S$ is Clifford because it permutes Paulis:

$$S X S^\dagger = Y, \qquad S Z S^\dagger = Z.$$

$T$ is not: $T X T^\dagger = (X+Y)/\sqrt{2}$, which is not a Pauli. So $T$ is the smallest non-Clifford gate in this family.

Two theorems make that boundary the whole story:

  • Gottesman–Knill: Clifford circuits are efficiently simulable classically, so Clifford alone is not universal.
  • Eastin–Knill: no quantum error-correcting code implements a universal logical gate set transversally. Surface codes make Clifford gates cheap (transversal or lattice surgery), so the non-Clifford gate is the one that cannot be.

Why $T$ is the bottleneck

Two costs stack on $T$ and on nothing else.

  1. Magic-state distillation. $T$ is realized by injecting $|T\rangle = (|0\rangle + e^{i\pi/4}|1\rangle)/\sqrt{2}$ and teleporting. The injected state is noisy, so it is distilled. The 15-to-1 Bravyi–Kitaev protocol consumes 15 noisy $T$ states and outputs one with error $\approx 35p^3$. At $p = 10^{-3}$ that is $3.5\times10^{-8}$, not yet $10^{-9}$, so a second round is cascaded, and each round multiplies the input-state cost by 15. The physical footprint scales with code distance, not with gate count.

  2. Synthesis. An arbitrary $R_z(\theta)$ must be approximated by a Clifford+$T$ word. Solovay–Kitaev gives $T$-count $O(\log^{3.97}(1/\epsilon))$; optimal number-theoretic synthesis (Ross–Selinger) gives $\approx 3\log_2(1/\epsilon)$. At $\epsilon = 10^{-10}$ that is ~100 $T$ gates for a single rotation.

So a fault-tolerant circuit's cost is set by $T$-count and $T$-depth, not by its Clifford gates. Compilers targeting Clifford+$T$ (Qiskit's Clifford+$T$ passes, $T$-par optimization) treat Clifford as free and minimize $T$.

GateDiagonalGroupSurface-code implementation
$Z$$[1, -1]$Paulivirtual / frame update, zero physical cost
$S$$[1, i]$Cliffordtransversal or lattice surgery, low overhead
$T$$[1, e^{i\pi/4}]$non-Cliffordmagic-state injection + distillation, high overhead

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Design and validate a circuit workflow for phase gates.

Answer

Core answer

Phase gates are Z rotations, so the workflow is: one convention, virtual-Z for every Rz the compiler can track, and a Ramsey fringe that measures the rotation angle rather than just checking the gate did something.

Convention: Rz(θ) = diag(1, e^{iθ}), θ in radians. Qiskit's rz(θ) = diag(e^{-iθ/2}, e^{iθ/2}) is the same gate up to the unobservable global phase e^{iθ/2}, so either convention gives identical measurement statistics. S = Rz(π/2), T = Rz(π/4), Z = Rz(π).

Implementation: on IBM superconducting backends Rz(θ) is a virtual-Z frame change. Zero duration, zero error, any θ, including T. The Clifford/non-Clifford split decides fault-tolerance cost (T needs magic-state distillation in a surface code), not the physical implementation. You fall back to a physical Z only when the compiler cannot track the frame.

Validation: Ramsey fringe

Prepare |+>, apply the gate, analyse with Rz(-φ), measure in the X basis. Then P(|0>) = cos²((θ-φ)/2).

Python
# Qiskit 1.x. rz(θ) = diag(e^{-iθ/2}, e^{iθ/2}) = diag(1, e^{iθ}) up to global phase.
import numpy as np
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector

def ramsey(theta, phi):
    qc = QuantumCircuit(1)
    qc.h(0)              # |+>
    qc.rz(theta, 0)      # gate under test
    qc.rz(-phi, 0)       # analysis rotation
    qc.h(0)              # rotate to X basis
    return qc

def p0(theta, phi):
    return Statevector(ramsey(theta, phi)).probabilities()[0]

p0(np.pi/2, 0.0)   # 0.5    ideal S, measured on the slope
p0(90.0, 0.0)      # 0.276  degrees bug: 90 rad ≡ 2.035 rad

Trace: θ=π/2, φ=0 → Δ=π/2 → P(|0>)=cos²(π/4)=0.5. For the bug, Δ=90 rad ≡ 1.018 rad after removing 7·2π, so P(|0>)=cos²(1.018)=0.276.

Measure on the slope, not the null. At φ=θ the fringe peaks at P=1, but sensitivity is quadratic: a phase error δ moves P by δ²/4. At φ=θ-π/2, P=0.5 and dP/dθ=-1/2, so the same δ moves P by δ/2: linear. Shot noise at p=0.5 with N=1000: σ=√(0.25/1000)=0.0158, 3σ=0.047, so the slope resolves δθ≈0.094 rad (5.4°). Reaching 0.5° needs ~1.2×10^5 shots. To recover the angle and its sign, sweep φ over 0..2π and fit P(|0>)=(1+cos(θ-φ))/2.

Alternatives

ImplementationDurationErrorUse when
Virtual Z (frame change)00Compiler tracks the frame: default for every Rz on IBM superconducting hardware
Physical Z1–2 pulses~0.5% (hypothetical)Hardware or compiler without frame tracking
Absorb into measurement00Rz is the last gate before a Z-basis measurement

Deciding criterion: if the compiler tracks the frame, virtual; otherwise physical. Interference is the right validator here because it is phase-specific and cheap; process tomography scales exponentially in qubits and randomized benchmarking returns an average error that hides a phase-only fault.

Failure modes

  • Degrees/radians. Passing 90 where π/2 rad is expected applies Rz(90) ≡ Rz(2.035 rad). The slope point reads P(|0>)=cos²(1.018)=0.28 instead of 0.5: a 14σ deviation, caught in one run.
  • Sign convention. Rz(-θ) instead of Rz(θ): the slope point still reads cos²(-π/4)=0.5, so a single-point check misses it. The fringe fit returns -π/2 instead of +π/2.
  • Global vs relative phase. Global phase is unobservable; the bug is trying to cancel it with an extra pulse, which injects a relative phase. Detection: the fitted fringe phase shifts.
  • Serialization. A QASM round-trip that writes s (diag(1,i)) and reads back sdg (diag(1,-i)) flips the relative phase. Detection: serialize, deserialize, fit the fringe; the sign flips.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Design and validate a circuit workflow for rotation gates.

Answer

Core answer

A rotation-gate workflow is a pipeline that takes a symbolic angle, proves it valid, binds it to a number, and proves the bound circuit still computes what the symbolic one claimed. The gates are RX, RY, RZ, each exp(−iθP/2) for P ∈ {X, Y, Z}. The angle is in radians; observable expectations are 2π-periodic, the unitary is 4π-periodic. I'll assume Qiskit 1.x and radians, and flag where PennyLane differs.

Five stages, each with a check that can fail:

  1. Template: declare Parameter("theta"), build qc.rx(theta, 0). No numbers yet.
  2. Domain: reject non-finite or non-real values before binding.
  3. Bind: assign_parameters({theta: v}) returns a new circuit; assert len(bound.parameters) == 0.
  4. Record: keep the ParameterExpression, the unit, and the float precision. Statevector is complex128; AerSimulator(precision="single") is not.
  5. Validate: compare the bound circuit to the analytic matrix, and the gradient to the parameter-shift rule.
Python
from qiskit import QuantumCircuit
from qiskit.circuit import Parameter
from qiskit.quantum_info import Statevector
import numpy as np

theta = Parameter("theta")
qc = QuantumCircuit(1)
qc.rx(theta, 0)

def bind(circ, value):
    v = float(value)
    assert np.isfinite(v), "non-finite angle"
    bound = circ.assign_parameters({theta: v})
    assert len(bound.parameters) == 0, "unbound parameter remains"
    return bound

sv = Statevector(bind(qc, np.pi / 3))
print(sv.probabilities())         # [0.75, 0.25]
print(sv.expectation_value("Z"))  # 0.5

RX(π/3)|0⟩ = cos(π/6)|0⟩ − i sin(π/6)|1⟩, so probabilities are 0.75/0.25 and ⟨Z⟩ = cos(π/3) = 0.5. That is the analytic check.

The gradient check uses the parameter-shift rule, exact for these gates because the generator P has eigenvalues ±1:

quantityvalue
⟨Z⟩(θ)cos θ
∂⟨Z⟩/∂θ at θ = π/3−sin(π/3) = −0.8660254
(⟨Z⟩(θ+π/2) − ⟨Z⟩(θ−π/2))/2(cos 5π/6 − cos(−π/6))/2 = (−0.8660254 − 0.8660254)/2 = −0.8660254

The shift is π/2, not π. PennyLane's qml.gradients.param_shift uses the same π/2 for qml.RX.

Trade-offs

Parameter-shift costs two circuit evaluations per parameter and is exact; finite difference costs two but is O(ε) wrong and noisy on hardware; backprop is exact and cheap on a simulator but unavailable on hardware. Bind symbolically when the same template runs many angles (one transpile, many binds) and bind to floats early when you only run once.

Failure modes

  • Unbound parameter: simulation and submission both reject a circuit with free parameters. Detect with len(qc.parameters) == 0 before either.
  • Unit mismatch: degrees passed where radians are expected. Detect by evaluating at θ = π/2, where ⟨Z⟩ must be 0.
  • Periodicity: wrapping θ mod 2π changes the statevector by a global phase −1, so a statevector-equality test fails and a controlled rotation is genuinely wrong. Detect by comparing Statevector before and after wrapping.
  • Gradient convention: a framework defining the gate as exp(−iθP) rather than exp(−iθP/2) needs a π shift, not π/2. Detect by finite-difference cross-check at one parameter.
  • Backend approximation: transpiling to a discrete basis synthesizes arbitrary angles with error, and approximation_degree controls how much. RZ is usually virtual and exact; RX/RY need pulses. Detect by comparing the transpiled statevector to the original.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Design and validate a circuit workflow for controlled operations.

Answer

Core answer (first 90 seconds)

Assume Qiskit 1.x with Aer, a two-qubit CX as the canonical case, and one question that decides the whole plan: is the control supposed to stay coherent (algorithmic. Phase kickback, controlled-Rz, Grover diffusion), or is a mid-circuit measurement intended (feed-forward. Teleportation's conditional X/Z, syndrome correction)? Coherent means validate the phase; feed-forward means validate the classical path. Then: sweep the four basis states, add a superposed control, and check statevector fidelity against the ideal, not just counts.

Why basis states aren't enough

CX applies X to the target only in the control=1 subspace: CX|10> = |11>, CX|00> = |00>. Sweeping |00>, |01>, |10>, |11> verifies that truth table and catches reversed operands: CX(0,1) and CX(1,0) differ exactly on |01> and |10>. But every basis state is a computational-basis state, so the control is never in superposition and no coherence is exercised. A control that has been measured, reset, or replaced by a classical if passes all four.

The coherence test

Prepare |+>|0>; after CX it is (|00>+|11>)/√2, a Bell state. Counts alone can't confirm it: 4096 shots give ~2048 on 00 and ~2048 on 11, and so does a 50/50 classical mixture of |00> and |11>. Separate them by applying H to both qubits before measuring. H⊗H maps the Bell state to (|00>+|11>)/√2: even parity only. The classical mixture maps to a uniform 25% over all four outcomes. So the witness is: even parity only ⇒ coherent; all four outcomes ⇒ the control was collapsed.

Python
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector, state_fidelity

def bell():
    qc = QuantumCircuit(2)
    qc.h(0)
    qc.cx(0, 1)
    return qc

ideal = Statevector(bell())                 # built from |00>
print(ideal.probabilities_dict())           # {'00': 0.5, '11': 0.5}
print(state_fidelity(ideal, Statevector(bell())))  # 1.0 on the simulator

witness = bell()
witness.h(0); witness.h(1)
witness.measure_all()                       # expect only 00 and 11

On the simulator, fidelity ≥ 0.999 (exact up to float error). On hardware, run the witness with 4096 shots and compare parity visibility against the device's reported error rates.

Failure modes and how they show up

failurepassesfails
implicit measurement (measure/reset on control)basis sweepparity test: all four outcomes
reversed operands, CX(1,0)superposed countsbasis sweep on |01>, |10>
classical if on a measured controlbasis sweep, superposed countsparity test
decoherence / gate noise—fidelity < 0.999 on sim; parity visibility drops on hardware

Trade-offs

Coherent vs classical: coherent control is required whenever the control's phase matters. Phase kickback in QFT, Grover's diffusion, controlled-Rz. Classical feed-forward is correct and cheaper when you genuinely want a mid-circuit measurement, e.g. teleportation's conditional X/Z. Don't "fix" feed-forward into coherent control; you'd add a gate you don't need and lose the measurement you do.

Simulator vs hardware: statevector gives exact fidelity for free but no noise; hardware needs shots and a coherence witness. On current superconducting devices CX error is ~0.5–1% and readout error ~1–3%, so parity visibility won't be 100%: set the threshold from the device's reported error rates, not from 1.0. 4096 shots gives ±0.8% (1σ) on a 50/50 outcome; to resolve a 2% deviation at 3σ you need ~5600 shots.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Design and validate a circuit workflow for SWAP.

Answer

Assumptions: a fixed coupling map (here a 5-qubit line 0–1–2–3–4), CX as the only two-qubit basis gate, and a device whose calibration we can read. Tooling is Qiskit 1.x (transpile, SabreSwap).

Core answer. A SWAP workflow has four stages: choose a layout, route, record the layout permutation, and validate equivalence plus cost. Routing exists because a two-qubit gate can only execute on an edge of the coupling map. When the operands land on non-adjacent physical qubits, the compiler inserts SWAPs along a shortest path to bring them together. A SWAP is not a primitive, it decomposes to three CX, so every hop costs three CX.

Mechanism and cost. For a CX between logical qubits that land on physical 0 and 4 of a line, the shortest path is 4 edges. Moving one operand three steps makes them adjacent: 3 SWAPs = 9 CX, plus the CX itself = 10 CX. If you also restore the original layout (uncompute the SWAPs) it is 6 SWAPs + 1 CX = 19 CX. At a per-CX fidelity of 99.5%, 10 CX gives 0.995^10 ≈ 95.1% success versus 99.5% for a single CX: the routing decision is a fidelity decision, not just a depth one.

Trade-offs. Sabre routing is the Qiskit 1.x default: heuristic, scales to hundreds of qubits, near-optimal on most circuits. Lookahead routing searches deeper and can shave SWAPs on small circuits but costs compile time. Basic routing is greedy and usually worst. Layout choice matters more than routing method: trivial keeps logical→physical identity (cheap to reason about, expensive to route), dense/sabre minimize distance. Decide by circuit width vs device width and by CX error rate: if CX error is 1e-2, an extra SWAP costs ~3% fidelity, so pay compile time for Lookahead; if it is 1e-3, Sabre's speed wins.

Validation. Two checks. Equivalence: transpile with optimization_level=0 and compare Operator.from_circuit(tqc) against the original up to the final permutation. Cost: tqc.count_ops() CX count against the theoretical 3×(SWAPs)+1. Record tqc.layout.final_index_layout() and apply its inverse to measurement bitstrings.

Python
from qiskit import QuantumCircuit, transpile
from qiskit.transpiler import CouplingMap
from qiskit.providers.fake_provider import GenericBackendV2

backend = GenericBackendV2(num_qubits=5, coupling_map=CouplingMap.from_line(5), seed=42)
qc = QuantumCircuit(5); qc.cx(0, 4)

tqc = transpile(qc, backend, routing_method="sabre", layout_method="sabre",
                optimization_level=1, seed_transpiler=42)
print(tqc.count_ops()["cx"], tqc.layout.final_index_layout())

The check is that the CX count equals 3×(SWAPs inserted)+1; Sabre's exact count depends on the seed, which is why seed_transpiler is pinned.

Failure modes and detection.

failuresymptomdetection
layout lostresults come back in physical orderfinal_index_layout() missing or identity when routing occurred; prepare |10000⟩ on logical 0 and check which physical qubit reads 1
stale calibrationrouting picks a high-error edgecompare the backend's calibration timestamp (backend.properties().last_update_date on BackendV1, backend.target on BackendV2) to job time; re-transpile if older than the device's calibration window
SWAP direction errorCX applied in the wrong directioncheck each CX against the directed CouplingMap edges; on hardware CX(q0,q1) ≠ CX(q1,q0)
hidden two-qubit expansiona "SWAP" counted as one gatecount_ops() before/after; transpile to basis_gates=['cx','u'] and recount
logical decoded as physicalwrong bitstringapply the inverse final layout; cross-check with a known basis state

When not to route. If the circuit is small enough to fit the coupling map with a good layout, skip SWAPs entirely: a trivial layout with zero routing beats any heuristic. Routing is a cost you pay only when the interaction graph does not embed in the device graph.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Design and validate a circuit workflow for parallelism and depth.

Answer

Core answer

Depth is the length of the longest dependency chain in the circuit's DAG, counted in abstract layers. It is not wall time. Two gates are parallel when they act on disjoint qubits and neither depends on the other, so depth is a property of the circuit plus the coupling map, while wall time is a property of the circuit plus the control electronics. The workflow reports four numbers separately (gate count, depth, two-qubit depth, and scheduled duration) because they answer different questions and diverge the moment you transpile.

Assume a fixed target backend with a known basis gate set, coupling map, and pulse durations. Without those, depth is target-independent and only useful as a relative baseline.

Design

  1. Build the logical circuit.
  2. Transpile to the target at a chosen optimization level, with a scheduling method.
  3. Read the four metrics off the transpiled circuit.
  4. Validate by re-running with the other scheduling method and asserting depth is unchanged.
Python
# Qiskit 1.x
from qiskit import QuantumCircuit, transpile

qc = QuantumCircuit(3)
qc.h(0); qc.cx(0, 1); qc.cx(1, 2); qc.h(2)

for method in ("as_soon_as_possible", "as_late_as_possible"):
    tqc = transpile(qc, backend=backend, optimization_level=3,
                    scheduling_method=method)
    print(method, tqc.depth(), tqc.count_ops(), tqc.duration)

Trace

On the logical circuit, h(0) and h(2) are disjoint, so they share layer 0. cx(0,1) depends on h(0) and lands in layer 1. cx(1,2) depends on cx(0,1) and lands in layer 2. Depth = 3, gate count = 4, two-qubit depth = 2. After transpiling to a real backend, h becomes sx+rz and cx may become ecr, so all four numbers change: that is why you report the transpiled circuit, not the logical one.

Table

metricmeasuressourceblind spot
gate counttotal opscount_ops()critical path
depthlongest dependency chain, layerscircuit.depth()wall time
two-qubit depthlongest 2q chaindepth of the 2q-only subcircuitcrosstalk serialization
scheduled durationpulse time on target, in dtcircuit.duration after schedulingportability

Trade-offs

ASAP and ALAP produce the same depth for a fixed circuit but place slack differently: ASAP starts gates early, ALAP pushes them late to sit next to measurement. That matters when you insert dynamical decoupling or when the control electronics enforces a minimum pulse spacing. optimization_level 0 compiles fast and leaves depth high; level 3 spends seconds to minutes of compile time to cut depth. Pick by whether compile time or depth is the binding constraint.

Failure modes and detection

  • Depth quoted as wall time: compare depth (layers) to duration (dt). If they are the same number, one is mislabeled.
  • Crosstalk ignored: the abstract DAG schedules adjacent-qubit gates in parallel; the hardware serializes them. Detect by comparing scheduled duration to measured wall time on hardware: a gap means the schedule is optimistic.
  • Barriers abused: qc.barrier() forces a scheduling boundary and blocks optimization. Detect by diffing depth with and without barriers.
  • Target-independent comparison: depth across backends with different basis gates and coupling maps is not comparable. Detect by checking count_ops() matches before comparing.

Validation

Run both scheduling methods and assert depth is identical: it must be, since scheduling does not change the DAG. Duration will differ. If depth changes, a barrier or a pass is reordering the circuit, and the workflow is measuring the wrong thing.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-16

Design and validate a circuit workflow for inverse circuits.

Answer

Assumptions. "Inverse circuit" here means the adjoint U† of a unitary circuit U: the operation that undoes it. I'll use Qiskit 1.x as the concrete framework; the same structure holds for cirq.inverse and qml.adjoint. "Workflow" means the build-and-validate path: construct the inverse, then prove it cancels.

Core answer. Build the inverse by reversing the instruction order and inverting each instruction. Self-inverse gates (X, Y, Z, H, CNOT, CZ, SWAP) are unchanged; parameterized gates negate their angle (Rz(θ) → Rz(−θ)); non-self-inverse gates map to their dagger (S → S†, T → T†). Validate with one composition: build U, build U†, compose them, and assert the result is the identity up to global phase. Reject any circuit containing a non-invertible instruction (measurement, reset, or classical feedforward) because those are not unitary and have no adjoint.

Why reversal: matrix product. If U = G_n ⋯ G_1, then U† = G_1† ⋯ G_n†. The order flips because (AB)† = B†A†.

Python
from qiskit import QuantumCircuit
from qiskit.quantum_info import Operator

qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.rz(0.3, 1)
qc.s(0)

inv = qc.inverse()                 # reverse order, invert each gate
combined = qc.compose(inv)         # apply qc, then inv
print(Operator(combined).equiv(Operator(QuantumCircuit(2))))

Trace: qc is H(0), CX(0,1), Rz(0.3,1), S(0). inverse() yields S†(0), Rz(−0.3,1), CX(0,1), H(0). Composed, the middle pairs cancel: S·S† = I, Rz(0.3)·Rz(−0.3) = I, CX·CX = I, H·H = I. The product is the identity, so equiv prints True. equiv compares up to global phase; == would fail on a phase difference no experiment can see.

Trade-offs in validation. Operator builds the full 2ⁿ × 2ⁿ matrix: exact, but memory blows up past roughly 10–12 qubits. Above that, use statevector checks on a handful of random inputs, or restrict to Clifford circuits where stabilizer comparison is polynomial. Structural checks (does the gate list reverse and invert?) are cheap but miss a wrong parameter sign.

Failure modes.

FailureSymptomDetection
Order not reversedU·U† ≠ Iequiv returns False
Parameter sign not negatedRz(θ)Rz(θ) = Rz(2θ)unitary check fails; angle doubles
Measurement / reset presentinverse() raises CircuitErrorbuild-time error
Transpiled separatelytwo decompositions don't cancelcompose after transpiling both
Global phase compared exactlyfalse failureuse equiv, not ==

When not to use. If the circuit is not unitary (mid-circuit measurement with feedforward, or a noisy channel) there is no inverse circuit; you need the inverse channel or classical post-processing instead. And when every gate is self-inverse, re-running the same circuit is the inverse and cheaper than building an explicit adjoint.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15

Design and validate a circuit workflow for global phase.

Answer

Core answer. Global phase is unobservable on a standalone state, so a rewrite that changes it is safe, until the subcircuit is controlled or embedded in a block-encoding, where that phase becomes relative and observable. The workflow is therefore: classify each rewrite by whether it can ever be controlled, pick the equivalence relation to match, and validate with the metric that matches the relation.

Assumptions: exact-arithmetic simulation for the unit checks; the rewrite is a gate-definition substitution (the running example is S → RZ(π/2), a real rewrite because RZ is native on many backends and S is not); the compiler carries a global-phase field.

Design.

  1. Classify the rewrite. Can this subcircuit ever appear under a control, inside a block-encoding, or as a term in a larger unitary whose off-diagonal phase matters? If no, global phase is free. If yes, it is not.
  2. Pick the equivalence relation. Uncontrolled: U ~ V iff U = e^{iφ}V, tested with the normalized trace |Tr(U†V)|/d = 1. Controlled or embedded: U = V exactly, or U = e^{iφ}V with φ recorded and re-applied as a relative phase at control time.
  3. Represent the phase explicitly. Keep a global-phase field (Qiskit's GlobalPhaseGate, or Operator.global_phase) and propagate it through every optimization pass instead of letting each pass drop it.
  4. Validate at the level the circuit will be used: unit-test the uncontrolled equivalence with the phase-insensitive metric, unit-test the controlled version with the phase-sensitive one, and add one end-to-end interference regression.
contextequivalencemetrictolerance
uncontrolled, measurement-onlyup to global phase|Tr(U†V)|/d1e-8
controlled / block-encodingexactmax elementwise |U−V|1e-10
statevector simup to global phase, phase tracked|Tr(U†V)|/d1e-10
sampler / density matrixup to global phasetotal-variation of bitstring distribution1e-3 (shot noise)
Python
import numpy as np
from qiskit import QuantumCircuit
from qiskit.quantum_info import Operator

def equiv_up_to_phase(U, V, tol=1e-8):
    d = U.data.shape[0]
    return abs(np.trace(U.data.conj().T @ V.data)) / d > 1 - tol

s  = QuantumCircuit(1); s.s(0)
rz = QuantumCircuit(1); rz.rz(np.pi/2, 0)
U, V = Operator(s), Operator(rz)

print(equiv_up_to_phase(U, V))                        # True
print(equiv_up_to_phase(U.control(1), V.control(1)))  # False

Worked trace. S = diag(1, i) and RZ(π/2) = diag(e^{−iπ/4}, e^{iπ/4}) = e^{−iπ/4}·S.

  • Uncontrolled: |Tr(S† RZ(π/2))|/2 = |2e^{−iπ/4}|/2 = 1.000 → equivalent.
  • Controlled: CS = diag(1,1,1,i), CRZ = diag(1,1,e^{−iπ/4},e^{iπ/4}); |Tr(CS† CRZ)|/4 = |2 + 2e^{−iπ/4}|/4 = cos(π/8) ≈ 0.924 → not equivalent.
  • Fix: controlled-S = (P(π/4) ⊗ I)·controlled-RZ(π/2). The rewrite must record φ = π/4 and insert P(π/4) on the control when the gate is later controlled.

Failure modes.

  1. Controlled-global-phase bug: rewriting S → RZ(π/2) and then controlling it. Detected by the controlled metric above (0.924 ≠ 1), or by running controlled-S on |11⟩ and checking the phase is i. Cost: a silent wrong phase in phase estimation or block-encoding.
  2. Phase dropped by a pass: an optimizer sets global phase to 0. Detected by comparing Operator.global_phase before and after, or a Ramsey interference test.
  3. Relative phase mistaken for global: treating diag(1, e^{iθ}) as free. Detected by measuring in the X basis; the off-diagonal of ρ changes.
  4. Metadata applied twice: the phase field is re-applied at both rewrite and control time. Detected by end-to-end unitary comparison against a golden reference.

Trade-offs. Dropping phase everywhere is cheapest and gives the smallest circuits, but is valid only if nothing downstream controls the subcircuit. Tracking phase as metadata is standard (Qiskit, TKet) and costs bookkeeping plus double-application risk. Canonicalizing to a phase-free form (fix the first nonzero element real) makes equivalence exact but can block gate-level optimizations. Validating by sampling only is cheap and phase-blind, valid only for uncontrolled measurement-only circuits. The deciding criterion is whether the subcircuit is ever controlled or embedded, and whether the consumer is a statevector (phase-sensitive) or a sampler (phase-blind).

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Design and validate a circuit workflow for decomposition.

Answer

A decomposition is correct only relative to a target and a validation method. I start by pinning the target: basis_gates, coupling_map, native two-qubit gate, qubit count, and calibration error rates. Then I generate candidates and score them by native two-qubit gate count, depth, and estimated fidelity. Finally I validate equivalence up to the phase convention the surrounding circuit requires.

Mechanism. For blocks up to about 6 qubits, compute the unitary and compare up to global phase. Qiskit 1.x: Operator(circ).equiv(Operator(ref), rtol=1e-8, atol=1e-8). For larger blocks, use process tomography on 2–3 qubit subblocks or compare action on a random basis. For channels, use process_fidelity from qiskit.quantum_info. Cost differs because native gates differ: a Toffoli into Clifford+T costs 7 T gates and 6 CNOTs on a T-gate target; on a trapped-ion target with native RXX, the same Toffoli may cost fewer two-qubit gates but different single-qubit rotations. An arbitrary RZ to ε=10⁻¹⁰ costs on the order of 100 T gates via Ross–Selinger; a native RZ costs one RZ. So target-aware cost is not abstract gate count.

Trade-offs. T-count vs depth vs ancilla. Clifford+T Toffoli: 7 T, 6 CNOT, 0 ancilla. If you allow an ancilla and measurement, you can trade T-count for width. When not to use: if the target has a native Toffoli or native RZZ, don't decompose to Clifford+T; use the native gate. A wrong choice is decomposing to a basis that isn't native, then transpiling again, which adds two-qubit gates and error.

Failure modes and detection.

  • Wrong parameter convention: RZ(θ) vs RZ(−θ), or Qiskit little-endian ordering. Detect by unitary mismatch on random inputs.
  • Ancilla cleanup omitted: ancilla not returned to |0⟩. Detect by tracing out the ancilla and comparing the reduced channel, or measuring the ancilla in |0⟩.
  • Target direction ignored: CNOT reversed. Detect by unitary mismatch; check control/target explicitly.
  • Approximation undocumented: RZ approximated to ε. Detect by process tomography; state ε and T-count.
  • Global phase mishandled: a decomposition that is correct up to global phase for an uncontrolled block becomes wrong when the block is controlled. Detect by testing the controlled version, not just the block.

Worked check. Take CZ = H on target, CNOT, H on target. On |11⟩: H on target gives (|0⟩−|1⟩)/√2; CNOT flips target to (|1⟩−|0⟩)/√2 = −(|0⟩−|1⟩)/√2; H on target returns −|1⟩, so |11⟩ → −|11⟩. On |10⟩: H on target gives (|0⟩+|1⟩)/√2; CNOT flips target to (|1⟩+|0⟩)/√2; H on target returns |0⟩, so |10⟩ → |10⟩. That matches CZ. If the CNOT direction is reversed, the |10⟩ case fails, which is the first production miss.

Production review. Run the same unitary check on every decomposed block, then run the controlled version if the block is ever controlled. Log the target basis, the chosen decomposition, the native two-qubit gate count, and the measured process fidelity. If the fidelity drops below the target's calibration threshold, reject the decomposition and try the next candidate.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Design and validate a circuit workflow for universal gate sets.

Answer

Core answer

Clarify two things before designing: universal for what, and exact or approximate. A finite gate set G is universal for n-qubit quantum computation when the group it generates is dense in SU(2^n) up to global phase. No finite set is exactly universal for quantum computation: density is the strongest statement available. Exact universality exists only for restricted targets, e.g. reversible classical circuits, where {CNOT, Toffoli} generates the full permutation group.

The workflow is five stages, and validation is three independent checks rather than one:

  1. Fix the target unitary and the error metric: diamond norm ε, not fidelity.
  2. Choose the gate set from the hardware and the fault-tolerance requirement.
  3. Synthesize.
  4. Optimize against the cost metric that binds: T-count under fault tolerance, depth on NISQ.
  5. Validate universality (algebraic), approximation error (numerical), and resources (counting).

The decision that drives the rest is fault-tolerant or not. Fault-tolerant → Clifford+T, T-count is the cost, and magic-state distillation sets the physical price. NISQ → the native set, and depth and two-qubit count are the cost.

Mechanism

Stage 1, set selection. Superconducting hardware natively gives {CNOT, R_z(θ), √X}; trapped ions give {XX(θ), R_z(θ)}. If the native set is universal, use it. For fault tolerance, compile to Clifford+T = {H, S, CNOT, T}. {H, T} alone is dense in SU(2) (Boykin et al., 2000); adding CNOT gives n-qubit universality. {CNOT, H, S} is not universal: it generates the Clifford group, which is finite, so it cannot be dense.

Stage 2, synthesis. Decompose multi-qubit unitaries with the cosine–sine decomposition into two-qubit blocks, then handle each single-qubit rotation. If the target lies in the Clifford+T ring Z[1/√2, i] up to global phase, exact synthesis applies (Kliuchnikov–Maslov–Mosca, 2013) and the circuit is exact. Otherwise approximate, by one of two families:

  • Solovay–Kitaev: general to any universal set, O(log^{3.97}(1/ε)) gates (Dawson–Nielsen; Kitaev's variant gives log³).
  • Number-theoretic (Ross–Selinger, 2016): Clifford+T only, T-count ≈ 3 log₂(1/ε) + O(log log(1/ε)).

Stage 3, optimization. Phase-polynomial optimization (Amy–Maslov–Mosca, 2013) for {CNOT, X, R_z} blocks, template matching, T-par. T-count is the metric because each T consumes a distilled magic state: 15-to-1 distillation turns 15 noisy T states into one with p_out ≈ 35 p_in³ (Bravyi–Kitaev, 2005).

Stage 4, validation. Three checks:

(a) Universality: show the generated group is dense. Concretely, that the set contains a non-Clifford gate and an entangling gate, or verify numerically that it approximates a target non-Clifford gate to 10^-10.

(b) Error: simulate, compute process fidelity F = |Tr(U†V)|²/d², convert to diamond norm ||U−V||_◇ = 2√(1−F) for unitary channels, require ≤ ε. For k gates the triangle inequality gives total error ≤ Σ ε_i, so budget ε/k per gate.

(c) Resources: count T gates, CNOTs, depth; compare against the analytic scaling.

Trade-offs

Exact synthesis gives zero approximation error but only inside the ring; approximate synthesis covers everything and costs gates. Solovay–Kitaev is general but its constant is enormous; number-theoretic is Clifford+T-specific and roughly 2000× cheaper at ε = 10^-6. T-count versus depth: T-parallelization trades one for the other, and under a coherence budget depth can bind first.

Failure modes

  1. Assuming universality. {CNOT, H, S} looks complete but is the finite Clifford group. Detection: check the generated group is dense, or try to approximate T. Cost: the target unitary is unreachable.
  2. Budgeting in fidelity instead of diamond norm. A coherent phase error δ gives infidelity δ²/4 but diamond norm δ, so a 10^-6 diamond-norm error is only 2.5×10^-13 infidelity. Fidelity hides coherent errors that accumulate linearly. Detection: compute both.
  3. Ignoring per-gate accumulation. k gates at ε each give total ≤ kε. Detection: sum the per-gate diamond norms.
  4. Resource blow-up. Solovay–Kitaev at ε = 10^-10 gives ~1.1×10^6 gates; number-theoretic gives ~100 T gates. Detection: compare counted gates to the analytic scaling.

Artefacts

Gate setUniversal?SynthesisCost scaling
{H, T}Yes: dense in SU(2)SK / number-theoreticT-count ≈ 3 log₂(1/ε)
{H, S, CNOT}No: finite Clifford group——
{H, T, CNOT}Yes: dense in SU(2^n)SK / number-theoreticT-count ≈ 3 log₂(1/ε)
{CNOT, Toffoli}Exact for reversible classicalExact permutationExact

Arithmetic. ε = 10^-6: log₂(1/ε) = 19.93. Number-theoretic T-count ≈ 3 × 19.93 ≈ 60. Solovay–Kitaev gate count ≈ 19.93^3.97 ≈ 1.4×10^5. ε = 10^-10: log₂(1/ε) = 33.22. Number-theoretic ≈ 100 T gates. Solovay–Kitaev ≈ 33.22^3.97 ≈ 1.1×10^6.

Validation snippet (Python 3, numpy):

Python
import numpy as np

def rz(theta):
    return np.diag([np.exp(-1j*theta/2), np.exp(1j*theta/2)])

def process_fidelity(U, V):
    d = U.shape[0]
    return abs(np.trace(U.conj().T @ V))**2 / d**2

theta, delta = 0.1, 1e-6
U, V = rz(theta), rz(theta + delta)
F = process_fidelity(U, V)
print(F, 1 - F, 2*np.sqrt(1 - F))

Trace: U†V = R_z(δ), whose trace is e^{-iδ/2} + e^{iδ/2} = 2cos(δ/2). So F = 4cos²(δ/2)/4 = cos²(δ/2) = 1 − 2.5×10^-13 at δ = 10^-6, and the diamond norm is 2 sin(δ/2) = 10^-6. Output: 0.99999999999975 2.5e-13 1e-06.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Design and validate a circuit workflow for measurement instruction.

Answer

Measurement is the instruction that turns a qubit's amplitude into a classical bit and collapses the qubit. It is not unitary, so it never appears in an Operator; as a channel it is the instrument with Kraus operators M0 = |0⟩⟨0|, M1 = |1⟩⟨1|, and Σ M_i† M_i = I.

Assumptions I'd state up front: Qiskit 1.x, Aer for simulation, a backend that supports mid-circuit measurement and reset if the workflow needs them, and the Z basis unless a rotation says otherwise.

Design, five steps.

  1. Registers. QuantumRegister(n) and ClassicalRegister(n); each measure takes exactly one qubit and one clbit, so the widths have to match what you read out.
  2. Basis. The measure instruction is fixed to Z. X basis: H before it. Y basis: S† then H. The rotation is a circuit instruction, not part of measure.
  3. Mapping. One measure per qubit you actually need, qubit i → clbit i, written explicitly rather than leaning on measure_all()'s implicit register allocation.
  4. Placement. Terminal measurement, or mid-circuit with feed-forward. If a later gate depends on the outcome, either use if_test on hardware or apply the principle of deferred measurement: replace the classically controlled gate with a controlled gate and move the measurement to the end.
  5. Readout. Pull the classical register from the result and post-process, keeping the clbit-index → logical-bit map.

Trace (Y basis, deterministic).

Python
from qiskit import QuantumCircuit
qc = QuantumCircuit(1, 1)
qc.h(0)      # |0> -> |+>
qc.s(0)      # |+> -> |+i>
qc.sdg(0)    # |+i> -> |+>
qc.h(0)      # |+> -> |0>
qc.measure(0, 0)

Step by step: H|0⟩ = |+⟩; S|+⟩ = (|0⟩+i|1⟩)/√2 = |+i⟩; S†|+i⟩ = (|0⟩+|1⟩)/√2 = |+⟩; H|+⟩ = |0⟩. So 4096 shots give 4096 0. Delete the S† and H and you are measuring |+i⟩ in the Z basis, which is 50/50: that gap is the check that the rotation is doing the work.

Bell trace: H(0), CX(0,1) gives (|00⟩+|11⟩)/√2. Measuring q0 collapses to |00⟩ or |11⟩ with p = 1/2 each, and q1 then always agrees. 4096 shots → ~2048 00, ~2048 11, with 01/10 appearing only from readout error.

Trade-offs. Deferred measurement avoids needing dynamic-circuit support and keeps the circuit unitary until the end, but costs ancillas and controlled gates; mid-circuit measurement plus reset saves qubits but needs backend support and adds latency. Hardware feed-forward (if_test) is fast but backend-limited; post-selection in software is free but discards shots, and the cost grows as 2^k for k post-selected qubits. Shot count sets statistical error at ~1/√shots, so 4096 shots is ~1.6% standard error on a probability: more shots help only until readout error dominates.

Failure modes and detection.

  • Measurement reordered past a noncommuting gate: a gate after a measure on the same wire acts on the collapsed state. Detect by walking the DAG and asserting no op follows a measure on that wire, or by diffing the circuit before and after transpile.
  • Wrong clbit: measure(q0, c1) when you meant c0. Detect with a known-state test: prepare |1⟩ on q0, measure, assert the expected clbit reads 1.
  • Result reuse race: two measures writing the same clbit before the first is read, silently overwriting it. Detect by counting writes per clbit in the DAG.
  • Collapse ignored: using the pre-measurement statevector after a mid-circuit measure. Detect by saving the statevector after the measure: it must be a product state, not the entangled one.
  • Readout noise omitted: calibrate the assignment matrix by preparing |0⟩ and |1⟩ and measuring to get p(1|0) and p(0|1). With p(1|0) = 0.03 and p(0|1) = 0.06, a true 50/50 state reads P(0) = 0.5·0.97 + 0.5·0.06 = 0.515, i.e. 51.5/48.5: a 1.5-point bias you would otherwise blame on the circuit.

Validation is that same list run as tests: statevector simulation against the analytic state, a deterministic eigenstate test, the assignment matrix, then hardware counts compared to the noiseless simulation within the statistical plus readout bound.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Design and validate a circuit workflow for reset.

Answer

Reset is a non-unitary channel, not a gate. It discards whatever state the qubit holds and reprepares |0>. That one fact drives the whole workflow: simulators that track only unitaries can't do it, and on hardware it costs a measurement.

Assumptions: IBM Eagle r3 (a BackendV2), Qiskit 1.0, mid-circuit qubit reuse.

What a strong candidate says first. Write qc.reset(q). On hardware the backend expands it to a measurement plus a conditional X (feedforward), so reset inherits the readout error, ~1–3% per qubit on Eagle-class devices, and costs readout latency. On Aer's statevector simulator, reset samples a measurement outcome, collapses the state, applies X if the outcome was 1, and renormalizes. The unitary simulator rejects it outright.

Workflow.

  1. Check the target supports it. In Qiskit 1.0 IBM backends are BackendV2, so backend.configuration() no longer exists: use backend.operation_names:
Python
from qiskit_ibm_runtime import QiskitRuntimeService
backend = QiskitRuntimeService().least_busy(operational=True, simulator=False)
assert "reset" in backend.operation_names

If reset isn't in the target, transpile raises a TranspilerError rather than silently dropping it.

  1. Transpile and inspect: transpile(qc, backend, optimization_level=1).count_ops() should still show reset. The expansion to measure + conditional X happens in the control electronics, not in the transpiled circuit.

  2. Validate on the simulator, then on hardware.

Validation circuit. Prepare |1>, reset, measure:

Python
from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator

qc = QuantumCircuit(1, 1)
qc.x(0)        # |1>
qc.reset(0)    # -> |0>
qc.measure(0, 0)

print(AerSimulator(method="statevector").run(qc, shots=1000).result().get_counts())
# {'0': 1000}

Trace: x(0) → |1>. reset(0) → |0>. measure → 0 every shot, so {'0': 1000}. Swap in method="unitary" and Aer raises an error naming reset as unsupported: the check that reset is non-unitary.

On hardware the same circuit returns ~1–3% '1' from residual thermal population and readout error. That number is your reset fidelity; track it per qubit.

Reset destroys entanglement: the failure mode people miss. Resetting one qubit of a Bell pair is a partial trace, not a local operation:

Python
qc = QuantumCircuit(2, 1)
qc.h(0); qc.cx(0, 1)   # (|00> + |11>)/sqrt(2)
qc.reset(0)            # discard qubit 0
qc.measure(1, 0)
# ~{'0': 500, '1': 500}

Trace: after cx the pair is (|00>+|11>)/√2. reset(0) samples qubit 0 (0 or 1, 50/50) collapses, and flips qubit 0 back to |0>. Qubit 1 is left in the matching branch, so it reads 0 or 1 with equal probability. If your algorithm assumed qubit 1 kept its state, it didn't.

Choosing a mechanism. Latency and error figures below are typical Eagle-class values; read them off your own backend's properties.

MechanismLatencyResidualNeeds
passive (idle ~5·T1)~500 µs at T1 = 100 µsthermal ~1%nothing
active (measure + conditional X)readout + conditional, ~1–2 µsreadout error ~1–3%mid-circuit measurement + feedforward
fresh qubit00a spare qubit

Error accumulates. Ten resets at 2% each leave the qubit correct with 0.98^10 ≈ 0.82: an 18% chance of at least one error. Reuse a qubit only when the qubit budget forces it.

Failure modes and detection.

  • Reset unsupported by target: transpile raises TranspilerError. Detect before submitting by checking backend.operation_names.
  • Residual excitation: measure immediately after reset; a non-zero '1' count is the reset error. Run the same circuit with no reset to separate readout error from reset error.
  • Entanglement collapse: if a partner qubit's marginal distribution goes 50/50 after a reset, the reset traced it out. Detect with the Bell-pair test above.
  • Redundant reset at circuit start: IBM hardware re-initializes qubits between shots, so a leading reset on a qubit adds latency for nothing. Detect by checking whether the reset is the first op on that qubit.

Trade-offs. Active reset is fast but needs mid-circuit measurement and feedforward, and it inherits readout error. Passive reset needs no hardware support but costs ~5·T1 per reset: unusable inside a deep circuit. A fresh qubit is error-free but the scarcest resource. Pick by qubit budget and how many times you reset.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Design and validate a circuit workflow for virtual and physical qubits.

Answer

Core answer

Assume a fixed target backend with a known coupling map and a calibration snapshot, and a circuit written against logical qubits. The workflow is: bind a versioned target, transpile with an explicit or transpiler-chosen initial layout, record the layout objects, run, then decode counts through the final layout before comparing to the logical expectation.

The most common production bug is decoding with the identity map. Routing inserts SWAPs, each SWAP is 3 CX, and those SWAPs permute which physical qubit holds which logical qubit. Read clbit i as logical qubit i and you get a wrong answer that still looks like a plausible distribution.

Mechanism

Transpilation changes the mapping in three ways: it picks an initial layout (logical to physical), it routes non-adjacent two-qubit gates by inserting SWAPs, and it rewrites measurements onto the physical qubits that hold the logical qubits at the end. Qiskit exposes all of this on the transpiled circuit: tqc.layout.initial_layout, tqc.layout.final_layout, and tqc.layout.input_qubit_mapping. final_layout is the permutation left by routing; apply its inverse to map measured physical qubits back to logical labels.

Worked trace

Linear coupling map 0-1, 1-2, 2-3, 3-4. Circuit: H(q0), CX(q0,q1), measure both. Pin initial_layout={q0:0, q1:4}.

  • CX needs adjacency; q1 sits on physical 4, q0 on 0.
  • Routing swaps q1 toward q0: SWAP(3,4) puts q1 on 3; SWAP(2,3) puts q1 on 2; SWAP(1,2) puts q1 on 1.
  • CX(0,1) is now legal. Three SWAPs = 9 extra CX.
  • Final layout: q0 to 0, q1 to 1. Initial layout was q0 to 0, q1 to 4.

Measure physical 4 expecting q1 and you read an idle |0>. Decode through final_layout and q1 is on physical 1. (Figures illustrative; the exact permutation depends on the router and seed.)

Trade-offs

choicewhen it winscost
manual initial_layout + seed_transpilerreproducible bitstrings, known-good qubitsignores calibration drift
SabreLayout (transpiler-chosen)best fidelity on current calibrationlayout changes run to run
routing_method='sabre'fewest SWAPs on most circuitsheuristic, non-deterministic
routing_method='basic'predictable, easy to auditmore SWAPs, lower fidelity
optimization_level=3fewer gatesslower transpile

Deciding rule: pin layout and seed when you need to compare runs or reproduce a bug; let the transpiler choose when you only care about best fidelity on today's calibration.

Failure modes

  • Identity layout assumed: logical i is not physical i. Detect by asserting initial_layout is the identity when you rely on it.
  • Final layout omitted: routing permutes qubits. Detect by checking final_layout is trivial, or decode through it.
  • Bit order reversed: Qiskit is little-endian, so counts key '01' means clbit1=0, clbit0=1. Reading left-to-right as q0,q1 reverses the string.
  • Calibration drift: backend.properties().last_update_date ages; a layout chosen for good qubits last week may be stale. Re-transpile against a fresh snapshot.
  • Ancilla collision: qubits reserved for mid-circuit measurement or magic states must be excluded from the layout.

Validation

Compare transpiled 2Q gate count and estimated fidelity against the untranspiled circuit. On a 127-qubit heavy-hex device, typical median 2Q error is about 3e-3 and readout about 1e-2, so a circuit with 100 CX has roughly a 26% chance of at least one error (1 - 0.997^100). Assert the decoded distribution matches the logical expectation on a simulator before spending QPU time.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Design and validate a circuit workflow for routing.

Answer

Core answer. Routing is the transpiler stage that makes a logical circuit executable on hardware whose coupling map is not all-to-all. Before designing anything, pin three inputs: the coupling map (IBM heavy-hex is degree-3; a Google-style grid is degree-4), the native two-qubit gate and whether the device supports it in both directions, and the age of the calibration data you are routing against. The workflow is five stages: build the interaction graph, choose an initial layout, route by inserting SWAPs, optimize, validate. Validation is not "it compiled": it is functional equivalence, resource cost, and an estimated fidelity against the calibration you used.

Mechanism. A logical two-qubit gate between qubits that are not physically adjacent must be implemented through the connectivity that exists. The standard move is to insert SWAPs until the pair is adjacent, apply the gate, and optionally swap back. One SWAP decomposes into three CX gates, so every hop you add costs three native two-qubit gates plus the depth to schedule them. Routing is therefore a search over layouts and SWAP sequences that minimizes a cost function: usually CX count, sometimes depth, sometimes estimated error. The interaction graph (which logical qubits must interact) and the coupling graph (which physical qubits can) are the two objects the search reconciles.

Worked trace. Coupling map is a line 0, 1, 2. Circuit is a single CX(q0, q2). Initial layout is trivial: q0→0, q1→1, q2→2. Physical distance between 0 and 2 is 2, so they are not adjacent.

  1. Insert SWAP(1,2). Layout becomes q0→0, q1→2, q2→1.
  2. Apply CX(0,1), which now implements CX(q0, q2).
  3. Record final layout {q0:0, q1:2, q2:1}.

Cost: one SWAP = 3 CX, plus the logical CX = 4 CX total. If you swap back, 7. If you drop step 3, the measurement on physical qubit 1 gets attributed to q1 instead of q2 and every result is silently wrong: that is the "final permutation lost" failure.

Choosing a router.

methodsearch strategytypical CX overheadwhen it wins
basicgreedy, no lookaheadhighesttiny circuits, debugging the map
stochasticrandom trials, keep bestmoderatesmall devices, fast turnaround
sabrebidirectional heuristic with lookaheadlowest on averagedefault above ~20 qubits
noise-aware (tket CXMappingPass + NoiseAwarePlacement)cost includes per-edge errorhigher CX count, lower errordevices with uneven calibration

In Qiskit this is transpile(circ, backend, routing_method='sabre', optimization_level=3, seed_transpiler=42); the seed matters because SABRE is randomized and you want a reproducible artefact.

Validation. Three checks, in order. (1) Functional equivalence: strip measurements, then Operator.from_circuit(original).equiv(Operator.from_circuit(routed)). from_circuit accounts for the layout, and equiv compares up to global phase. (2) Resource cost: routed.count_ops() for CX count and routed.depth() for scheduling pressure. (3) Fidelity estimate: sum the per-edge CX error along each routed path from the calibration snapshot and compare against the unrouted estimate.

Failure modes and detection.

  • Shortest path assumed best. On heavy-hex, a 2-hop path through a high-error edge can lose to a 3-hop path through low-error edges. Detect by comparing estimated fidelity, not hop count.
  • Directionality ignored. If the device supports CX only one way, each reversed CX costs two extra H gates. Detect by diffing basis_gates against the directions you emitted.
  • Crosstalk absent. Simultaneous gates on adjacent pairs degrade fidelity. Detect with a noise model in AerSimulator or by checking backend.properties() for pair-level error.
  • Stale calibration. Calibration drifts between jobs. Detect by timestamping the snapshot and refusing to route against data older than your threshold.
  • Final permutation lost. Detect by asserting final_layout is present and that measurement mapping was rewritten.

When not to route this way. If the circuit is already all-to-all (trapped-ion, or a small fully-connected simulator), routing is a no-op and adding it only inflates depth. If the device exposes a native long-range gate, prefer it over a SWAP chain.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Design and validate a circuit workflow for basis translation.

Answer

What I'd say first

Three things decide this workflow, so I pin them before touching a compiler: which backend (and whether its target is static or drifts), whether the circuit is parameterized, and whether approximate synthesis is allowed. Default assumption: a fixed superconducting backend, static circuit, exact synthesis only.

The workflow is: freeze the target, translate against that frozen target, validate membership, validate semantics up to layout and global phase, then re-check the target fingerprint at submit time.

Mechanism

Basis translation is a DAG rewrite. The pass walks the circuit and, for every op whose name isn't in the target's operation set, looks up a decomposition rule and splices it in. rxx(θ) becomes two CX plus single-qubit rotations; a run of single-qubit gates gets re-synthesized into the target's 1q basis, which on IBM hardware is rz plus sx (or x). It runs after routing in the preset pass manager (layout, routing, translation, optimization, scheduling) which is why the decomposition has to respect CX direction: routing has already committed to physical qubits, and a reversed CX is not the same instruction on hardware where control and target are calibrated separately.

Trade-offs

optimization_level=0 still translates and routes but skips optimization; level 3 adds consolidation and re-synthesis, which is where approximate synthesis can creep in. approximation_degree=1.0 (the default) forbids it; anything lower lets UnitarySynthesis swap a gate for a close-but-not-equal unitary. That's the right call when you're compiling a large block you can't decompose exactly, and the wrong call when you're validating a logical identity. tket exposes the same choice through AutoRebase/SynthesiseTK versus FullPeepholeOptimise, and validates with predicates rather than asserts.

Failure modes

failuredetectioncost if missed
target drifted after compilehash operation_names + coupling edges + num_qubits at compile, compare before submitjob rejected, or worse, runs on a basis you didn't validate
control flow (if_else, for_loop)ControlFlowOp in the transpiled DAG; tket NoClassicalControlPredicateBasisTranslator has no rule for it and leaves it in place
reversed CXCheckGateDirection pass, or target["cx"][(q0,q1)] lookupwrong unitary, no error
duration not on the dt gridduration % target.dt == 0scheduling rejects or rounds
approximate synthesisOperator.from_circuit(isa).equiv(Operator(qc)) fails while the gate-set check passessilent fidelity loss

Code

Python
from qiskit import transpile
from qiskit.quantum_info import Operator

target = backend.target
cm = target.build_coupling_map()
fingerprint = (tuple(sorted(target.operation_names)),
               target.num_qubits,
               tuple(sorted(cm.get_edges())) if cm else None)

isa = transpile(qc, target=target, optimization_level=2,
                approximation_degree=1.0, seed_transpiler=1234)

assert set(isa.count_ops()) <= set(target.operation_names)   # membership
assert Operator.from_circuit(isa).equiv(Operator(qc))        # semantics

Operator.from_circuit is the part people get wrong: Operator(isa) compares the physical circuit without undoing the layout permutation, so it fails on a correct transpile.

Arithmetic

Hypothetical: 40 two-qubit gates, each approximated at process fidelity 0.999. 0.999^40 ≈ 0.961: a 4% fidelity loss that no gate-set check catches, because every gate is still in the basis. That's the number to put in front of whoever asks whether approximation_degree=0.99 is fine.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Design and validate a circuit workflow for optimization.

Answer

Assumptions. Qiskit 1.2 with qiskit-aer 0.14, a fixed 7-qubit target with a linear coupling map, and a source circuit in the standard gate set. "Optimization" here means cutting structural cost, depth and two-qubit gate count, of a circuit that is equivalent to the source for that target.

Core answer. The workflow has two halves that must be validated separately. Design: pin the input (circuit, backend, Qiskit version, seed_transpiler) and transpile at a fixed optimization_level, sweeping seeds because routing is stochastic. Validate: (a) semantic equivalence. The optimized circuit must implement the same unitary up to global phase; (b) target-aware execution. Depth, CX count, and measured fidelity on the device. Depth alone is a proxy, not a validation criterion; it can be gamed.

Mechanism. Qiskit's transpiler runs layout → routing → translation → optimization. Routing (SABRE) is a seeded heuristic search: different seeds insert different SWAPs, so the same input yields different depth and CX count. That is why pinning the seed is not optional: without it two runs of the same pipeline produce different circuits and no benchmark is reproducible. The optimization passes (peephole cancellation, template matching) are deterministic given the routed circuit, so the seed is the only source of run-to-run variance.

Python
# Qiskit 1.2, qiskit-aer 0.14
from qiskit import QuantumCircuit, transpile
from qiskit.quantum_info import Operator

qc = QuantumCircuit(3)
qc.h(0); qc.cx(0, 1); qc.cx(1, 2); qc.t(2); qc.cx(0, 2)

candidates = []
for seed in range(8):
    t = transpile(qc, backend=backend, optimization_level=3,
                  seed_transpiler=seed)
    if not Operator(qc).equiv(Operator(t)):   # up to global phase
        continue
    candidates.append((t.depth(), t.count_ops().get("cx", 0), seed, t))

candidates.sort()
depth, cx, seed, best = candidates[0]

Trace over seeds (illustrative figures for the 7-qubit linear target):

seeddepthCXequiv
04118True
13816True
24420True
33816True

Depth and CX do not move together: seeds 1 and 3 tie on both, seed 0 is deeper and has more CX. Reporting only the minimum depth (38) hides that half the seeds are worse: report the distribution.

Trade-offs. optimization_level 0–3. Level 1 is fast (sub-second on small circuits) but leaves SWAPs in; level 3 runs more routing and template passes, typically 2–5× the compile time for a few gates of depth. When compile time is the constraint (CI, or a large circuit), level 1 with a fixed layout beats level 3. Approximate synthesis: e.g. approximate Toffoli decompositions: trades exactness for gate count and is only valid if you re-check equivalence, which it will fail.

Failure modes and detection.

  • Nondeterministic build: transpile twice with the same seed and diff the QASM; a difference means a pass is unseeded.
  • Depth-only objective: track CX count and estimated error alongside depth. A pass that cuts depth by adding two-qubit gates raises error. Confirm on hardware by comparing measured fidelity of the two candidates.
  • Semantic regression: Operator.equiv on the full circuit plus a Statevector comparison on a random input; catches a pass that rewrites a gate into a non-equivalent one.
  • Compile timeout: set a wall-clock budget per transpile; on timeout fall back to optimization_level=1 or a precomputed layout.
  • Benchmark cherry-picking: report the distribution over seeds, not the minimum.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Design and validate a circuit workflow for serialization.

Answer

What a strong candidate says first

Ask what consumes the file before choosing a format. Three consumers, three answers:

  • A human, a paper appendix, or a non-Qiskit tool: OpenQASM 3. Text, versioned header (OPENQASM 3.0;), and it has a gphase gate, so global phase survives: OpenQASM 2 has no syntax for it and silently drops it.
  • A compiler or runtime: QIR, LLVM IR that carries classical control flow natively and is what compiled pipelines exchange.
  • A Qiskit pipeline that must round-trip losslessly: QPY, Qiskit's binary format. It stores global phase, custom gate definitions, and parameters as IEEE-754 doubles, and its header carries a format version.

The workflow is the same for all three: emit with an explicit version, re-parse the emitted bytes with a fresh reader, and assert equivalence on a canonical form rather than on the source object.

Workflow

  1. Serialize with a pinned writer version; record the format version in the artefact.
  2. Deserialize with a fresh reader in a separate process.
  3. Compare structurally (gate list, operands, parameters, classical flow, ordering) and semantically (unitary up to global phase, plus global phase exactly).
  4. Run the unsupported-feature checks below; each is a test, not a review note.

Artefact: round-trip check

Python
from qiskit import QuantumCircuit, qpy
from qiskit.quantum_info import Operator

qc = QuantumCircuit(2)
qc.h(0); qc.cx(0, 1); qc.rz(0.1, 1)
qc.global_phase = 0.3

with open("c.qpy", "wb") as f:
    qpy.dump(qc, f)
with open("c.qpy", "rb") as f:
    qc2 = qpy.load(f)[0]

assert Operator(qc).equiv(Operator(qc2))      # equal up to global phase
assert qc2.global_phase == qc.global_phase    # phase preserved exactly

Trace: qpy.dump writes the circuit and its global phase into the binary; qpy.load returns a list, so [0] is the circuit. Operator.equiv compares unitaries ignoring global phase, so it passes even if phase were lost: that is why the second assert exists. Swap qpy for qc.qasm() (OpenQASM 2) and the second assert fails: the phase is gone.

Failure modes, detection, cost

failurewhydetectcost
global phase lostOpenQASM 2 has no syntax; qasm() drops itOperator(a).data vs Operator(b).data element-wise, not .equivcontrolled version of the circuit is wrong; silent until it corrupts interference in a larger algorithm
precision losstext formats round parameters through decimal stringsassert bit-exact parameter equality after round-tripdrifts across transpile passes
condition droppedexporter ignores c_ifcount conditioned ops before and aftermid-circuit feed-forward silently becomes unconditional
register aliasingtwo measurements write the same creg bit; last write winsassert the qubit→bit map is injectiveone measurement result is lost
custom gate definition absentQASM 2 needs the gate declaration, not just the callparse the emitted file with a fresh parserfile fails to load at the consumer
version driftQPY header version exceeds the reader'sCI pins writer and reader versionsload raises; caught in CI, not in production

Decision

Default to QPY inside Qiskit, QASM 3 at any boundary a human or another tool reads, QIR when the next stage is a compiler. Whichever you pick, the round-trip test and the six checks above are the validation: a diagram is not an executable representation.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Design and validate a circuit workflow for semantic validation.

Answer

Core answer

Assume a reference circuit (the intended semantics), a compiled circuit targeting a fixed device, and a decision about what "same" means. Pin that first: for a unitary path, equivalence up to global phase; for a circuit with terminal measurements, equivalence of the classical outcome distribution, not just the unitary.

Run the cheapest checks first:

  1. Structural pre-check: qubit count, measurement count and positions, gate count within a factor of the reference. Catches wire permutation and dropped measurements before any simulation.
  2. Exact oracle for small n (n ≤ 12, where the 2^n × 2^n operator still fits in memory). Compare Operator(ref).equiv(Operator(compiled)) in Qiskit, which compares up to global phase at rtol=1e-5, atol=1e-8.
  3. Clifford path for large n. If both circuits are Clifford, compare stabilizer tableaus with stim: polynomial in qubit count, scales to thousands.
  4. Non-unitary path. For measured circuits, sample both and compare distributions with total variation distance, threshold ~0.02 at 10k shots.
  5. Validate the workflow itself by mutation testing: inject known bugs and confirm each is caught.

Mechanism

Why the inverse check works: if C' is meant to equal C, then C' C† = I. Simulate |0…0⟩ through C† then C'; any deviation from |0…0⟩ is a semantic mismatch. It is cheap because you need one statevector, not the full matrix.

Why global phase matters: e^{iφ}U and U are the same physical operation. np.allclose on raw matrices flags them as different: a false alarm. equiv factors the phase out.

Artefacts

Code (Qiskit 1.x):

Python
from qiskit import QuantumCircuit, transpile
from qiskit.quantum_info import Operator

ref = QuantumCircuit(3)
ref.h(0); ref.cx(0, 1); ref.cx(1, 2); ref.rz(0.3, 2)
compiled = transpile(ref, basis_gates=["rz", "sx", "cx"], optimization_level=3)

print(Operator(ref).equiv(Operator(compiled)))   # True

bad = compiled.copy(); bad.x(0)                  # inject a bug
print(Operator(ref).equiv(Operator(bad)))        # False

Trace: Operator(ref) is an 8×8 unitary. transpile with exact decompositions preserves it up to global phase, so equiv returns True. Adding an X(0) changes the unitary by a tensor factor, not a phase, so the second call returns False: the mutation is caught.

failurehow it hidesdetection
global phase false alarmraw matrix compare flags e^{iφ}compare up to global phase
measurement ignoredunitary equal, measurement placement differscompare outcome distributions
wire permutation hiddenendianness differs (Qiskit little-endian, Cirq big-endian)fix convention, compare with explicit permutation
approximate error unboundedtranspiler approximation accumulatesbound ‖U−U'‖ < 1e-6, track per-gate budget
shared-bug correlationsame simulator produces expected and actualindependent oracle (analytic, second simulator, hardware)

Trade-offs

Exact oracles are O(4^n) memory: fine to n≈12, useless beyond. Clifford tableaus are polynomial but only apply to Clifford circuits. Distribution tests scale to any size but only bound error statistically: at 10k shots you resolve TVD down to ~0.02, so a 1% semantic error slips through. Use exact where you can, statistical where you must, and never as the only check for a release gate.

Validating the workflow

The workflow itself needs a mutation test: seed a known bug (swap two CX controls, drop a measurement, add a phase) and confirm the corresponding check fires. If a mutation passes every check, the workflow has a hole. Shared-bug correlation is the subtle one, if the expected distribution comes from the same simulator under test, a wrong CX matrix cancels and the test passes. Break the correlation with an analytic expectation or a second backend.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Design and validate a circuit workflow for reproducible execution.

Answer

Core answer (say this first)

Reproducibility here is two claims, and they need different machinery. The artifact (the exact transpiled circuit, layout, parameters, shots) can be made bit-identical and hashed. The distribution from a real QPU cannot: there is no seed for hardware, and calibration drifts between runs. So the workflow pins the artifact exactly and bounds the distribution statistically. Assume Qiskit with qiskit-ibm-runtime on a superconducting backend, and a claim of the form "this figure came from this circuit."

The workflow

  1. Pin the toolchain. Record the Qiskit and qiskit-ibm-runtime versions and the QPY format version. Transpilation is not deterministic across versions even with the same seed.
  2. Transpile with an explicit seed and explicit layout/routing methods, against a snapshotted backend target.
  3. Serialize the transpiled circuit with QPY and SHA-256 the bytes. That hash is the artifact ID.
  4. Submit, and record the job ID, shot count, and the calibration snapshot the job ran under.
  5. Version the post-processing: hash the mitigation matrix and tie it to the same calibration snapshot.
Python
import hashlib
from qiskit import transpile, qpy
from qiskit_ibm_runtime import QiskitRuntimeService, SamplerV2

backend = QiskitRuntimeService().backend("ibm_brisbane")  # pin the device

isa = transpile(circuit, backend=backend, optimization_level=3,
                seed_transpiler=1234,
                layout_method="sabre", routing_method="sabre")

with open("circuit.qpy", "wb") as f:
    qpy.dump(isa, f)
artifact_id = hashlib.sha256(open("circuit.qpy", "rb").read()).hexdigest()

job = SamplerV2(mode=backend).run([isa], shots=4096)
manifest = {"artifact_id": artifact_id, "job_id": job.job_id(),
            "shots": 4096, "backend": backend.name,
            "calibration": job.properties().to_dict()}  # snapshot at run time

What is and isn't reproducible

LayerBit-identical?Pinned by
Source circuityesQASM 3 text + git SHA
Transpiled ISA circuityes, same Qiskit versionseed_transpiler, explicit layout/routing, target snapshot
Simulator countsyesseed_simulator + shots
Hardware countsno: distribution onlycalibration snapshot + job ID
Mitigation matrixyeshash tied to the calibration snapshot

Validating it

Re-run the same QPY on a simulator with the same seed: counts must match exactly, and any difference means the artifact or seed changed. On hardware, demand only statistical agreement. For a two-outcome circuit at 4096 shots, the standard error of the difference between two honest re-runs is sqrt(2·0.25/4096) ≈ 0.011, so a total-variation distance up to ~0.02 is shot noise; above that, suspect a changed artifact or drifted calibration. That threshold is a heuristic, not a test with a p-value.

Failure modes and how you catch them

  • Source–compiled mismatch: the QASM you reviewed isn't the ISA circuit that ran. Catch it by hashing the post-transpile circuit, not the source, and diffing the manifest hash against the re-loaded QPY. Silent otherwise: you debug a circuit that never executed.
  • Stale target: transpiled against last week's coupling map. Store the target snapshot hash and re-fetch backend.target to diff. Otherwise the layout lands on a qubit that is now offline.
  • Seed mistaken for hardware determinism: seed_simulator does nothing on a QPU. Catch it by running the same job twice and comparing: counts differ.
  • Calibration omitted: gate errors and T1/T2 drift, so a re-run weeks later gives a different distribution. Compare the recorded snapshot's error rates against the original.
  • Secrets logged: an API token in the manifest. Scan the manifest for credential fields; keep them out of the hashed artifact.
  • Post-processing unversioned: a readout-mitigation matrix built from a different calibration than the run. Hash the matrix and tie it to the snapshot ID.

Trade-offs

QPY is exact but opaque and version-locked; OpenQASM 3 is diffable but round-trips can drop register structure and pulse-level calibrations. Use QPY as the artifact of record, QASM 3 for review. If your claim is a simulator result, skip the calibration snapshot: it's irrelevant. If you're comparing across backends, the distribution test is meaningless; only the artifact hash carries over.

Curated: · Written: · Reviewed:

Difficulty: Hard