Skip to content
Tech Interview Prep
Technical interview guide

Qubits, Superposition & Quantum State Representation

How a qubit's state differs from a classical bit: superposition, the Bloch sphere, and bra-ket notation for describing quantum states.

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

Scope: IBM Quantum information and Qiskit current documentation; OpenQASM 3; QuTiP 5.4; Preskill notes; no-cloning and tomography source literature reviewed 2026-09-04.

Interview Q&A

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

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Represent and validate a quantum state for complex amplitudes.

Answer

Core answer (first 90 seconds)

I'd store the state as a dense complex array in a declared basis order, validate that the squared magnitudes sum to one within a tolerance tied to the dtype, and only ever derive probabilities as |amplitude|². Two things I pin down before writing code: the dtype, and the basis-ordering convention.

Assumptions: statevector simulation, n up to ~30 qubits, measurement in the computational (Z) basis, amplitudes in complex128.

Representation: a numpy.ndarray of complex128, shape (2**n,), where index i maps to basis state |i⟩ under a stated bit order. complex128 is 16 bytes per amplitude, so 30 qubits is 2³⁰ × 16 B = 16 GiB: that's the wall for dense simulation.

Validation: normalization is ⟨ψ|ψ⟩ = Σ conj(aᵢ)·aᵢ = 1. Compute np.vdot(psi, psi).real and compare with np.isclose(..., atol=1e-10). complex128 has machine epsilon ≈ 2.2e-16; after ~1000 gate applications the norm error accumulates roughly as O(√gates · ε) ≈ 7e-15, so 1e-10 leaves headroom without accepting a genuinely unnormalized state.

Why |a|²: the Born rule. P(i) = |aᵢ|² = re² + im². A global phase e^{iθ} multiplies every amplitude and cancels in |aᵢ|², so it is unobservable. Relative phase is what matters: amplitudes for the same outcome add before squaring, so it drives interference.

Python
import numpy as np

# |psi> = (|0> + i|1>)/sqrt(2); basis order: index 0 = |0>, index 1 = |1>
psi = np.array([1/np.sqrt(2), 1j/np.sqrt(2)], dtype=np.complex128)

norm = np.vdot(psi, psi).real          # <psi|psi>
assert np.isclose(norm, 1.0, atol=1e-10), f"not normalized: {norm}"

probs = np.abs(psi) ** 2               # Born rule

Trace: psi = [0.70710678+0j, 0+0.70710678j]. vdot conjugates its first argument, so conj(psi) = [0.70710678-0j, 0-0.70710678j]. Elementwise product with psi: 0.5 + 0j, and (-0.70710678j)(0.70710678j) = 0.5. Sum = 1.0, .real = 1.0, assertion passes. abs(psi) = [0.70710678, 0.70710678], squared = [0.5, 0.5].

Trade-offs

representation30-qubit memorywins whenbreaks when
dense complex12816 GiBgeneral circuits, high entanglement>~32 qubits
dense complex648 GiBtolerance ≥ 1e-6 is acceptablea 1e-10 normalization check is impossible
sparse dictO(nnz)few nonzero amplitudes (e.g. a GHZ state before measurement)entangling layers fill it in
MPS / tensor networkO(n·χ²)low-entanglement 1D circuitsvolume-law entanglement, χ explodes

Deciding criteria: qubit count, entanglement structure, and the tightest tolerance the downstream check needs. Pick complex64 only if you also loosen the tolerance: mixing them is a bug.

Failure modes

  • Amplitude treated as probability: probs = psi instead of np.abs(psi)**2. Catch it by asserting np.allclose(probs, np.abs(psi)**2) and that probs is real and nonnegative.
  • Imaginary part dropped: psi.real silently halves the norm. For the example above the norm becomes 0.5, so the normalization check catches it.
  • Basis unstated: index 1 is |01⟩ or |10⟩ depending on convention. Qiskit uses little-endian (qubit 0 = least significant); most textbooks are big-endian. A mismatch flips results for multi-qubit states while single-qubit checks still pass.
  • Rounding drift: after ~10⁴ gates the norm can read 0.9999999997. Renormalize only within tolerance; a state off by 10% is a bug, not drift.
  • Unauthorized normalization: silently rescaling a wrong state hides the defect. Reject outside tolerance, renormalize inside it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

Represent and validate a quantum state for normalization.

Answer

Core answer (first 90 seconds). Represent the state as a length-2^n complex128 array: one amplitude per computational basis state, indexed by bitstring. Validate by computing the squared norm Σ|a_i|² with np.vdot(psi, psi).real and comparing |Σ|a_i|² − 1| against a tolerance. For float64, 1e-9 is a defensible default: rounding error in the sum grows like √n·ε with ε = 2.22e-16, so at n = 2^30 amplitudes the typical error is ~7e-12, comfortably inside 1e-9. Then pick a policy (reject, renormalize, or warn) and say which, because the right one depends on where the amplitudes came from.

Why the modulus, not the square. A complex amplitude a_i contributes probability |a_i|² = a_i·conj(a_i). np.vdot(psi, psi) conjugates its first argument, so it computes exactly that sum. Writing psi @ psi instead gives Σa_i², which is wrong the moment any amplitude is complex: for [1/√2, 1j/√2] it returns 0.5 − 0.5 = 0 and the validator falsely reports a zero vector.

Python
import numpy as np  # numpy 1.26, Python 3.11

def validate_state(psi, tol=1e-9, policy="reject"):
    psi = np.asarray(psi, dtype=np.complex128)
    if not np.all(np.isfinite(psi)):
        raise ValueError("non-finite amplitude")
    norm_sq = np.vdot(psi, psi).real          # sum |a_i|^2
    if not np.isfinite(norm_sq) or norm_sq == 0.0:
        raise ValueError("zero or overflowing state")
    err = abs(norm_sq - 1.0)
    if err <= tol:
        return psi, err
    if policy == "renormalize":
        return psi / np.sqrt(norm_sq), err
    raise ValueError(f"norm^2={norm_sq:.3e}, off by {err:.3e}")

Trace.

  • psi = [1/√2, 0, 1j/√2]: vdot conjugates the first argument, so norm_sq = 0.5 + 0 + 0.5 = 1.0, err = 0.0 ≤ 1e-9 → returned unchanged.
  • psi = [0.5, 0.5]: norm_sq = 0.25 + 0.25 = 0.5, err = 0.5. With policy="reject" it raises; with policy="renormalize" it returns [0.70710678, 0.70710678], whose norm_sq is 1.0.

Choosing the policy.

policywhen it is rightwhat it costs
rejecttest suites, cross-checking a simulator against a referencefails loudly on legitimate hardware drift
renormalizeraw hardware output where shot noise and gate error shift the normsilently hides a bug in the state-preparation code
warn + logproduction pipelines that must keep runningdrift accumulates unnoticed unless you chart it

Failure modes to check for. NaN passes err <= tol as False and falls through to the reject branch, so test np.isfinite on the input explicitly rather than relying on that. Huge amplitudes overflow norm_sq to inf; check isfinite(norm_sq) before dividing. A zero vector makes np.sqrt(norm_sq) zero and the division produce NaN, so guard norm_sq == 0.0 first. A tolerance of 1e-12 looks strict but is tighter than the √n·ε floor for anything past ~20 qubits, so it rejects correct states; 1e-6 accepts states that are visibly wrong. Log the err value on every call: a norm drifting from 1e-15 to 1e-10 across a run is the earliest signal that something upstream broke.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

Represent and validate a quantum state for ket and bra.

Answer

Core answer

A ket is a column vector; a bra is its conjugate transpose, a row vector. Store the ket as shape (N, 1) with dtype complex128 and derive the bra: never store both, so they cannot drift apart.

Python
import numpy as np

ket = np.array([[1/np.sqrt(2)], [1j/np.sqrt(2)]], dtype=np.complex128)  # (2,1)
bra = ket.conj().T                                                       # (1,2)

Validation is the inner-product identity <psi|psi> == 1, which must come out real and nonnegative. Conjugation is what makes it true: each term is |c_i|^2, real and >= 0, so nothing cancels.

Trace it on the state above. bra @ ket = (1/sqrt2)(1/sqrt2) + (-i/sqrt2)(i/sqrt2) = 1/2 + 1/2 = 1.0+0j. Drop the conjugation, ket.T @ ket, and you get 1/2 + i^2/2 = 1/2 - 1/2 = 0: a normalized state reporting norm zero.

Python
def validate(ket, tol=1e-12):
    assert ket.ndim == 2 and ket.shape[1] == 1, "ket must be (N,1)"
    assert ket.dtype == np.complex128
    ip = ket.conj().T @ ket
    assert ip.shape == (1, 1), "inner product must be a scalar"
    assert abs(ip[0, 0].imag) < tol
    assert abs(ip[0, 0].real - 1.0) < tol

Alternatives and when to pick them

RepresentationShapeValidationUse when
NumPy ket + derived bra(N,1)`<psipsi> == 1`
Density matrix ket @ bra(N,N)trace == 1, rho == rho.conj().T, rho @ rho == rhomixed states, decoherence
QuTiP Qobj(N,1) + dimssame identity, plus basis metadatacomposite systems, tensor products

QuTiP's dims catches a basis reorder that NumPy silently accepts: worth the dependency once you build tensor products. For dtype, complex128 has eps ≈ 2.2e-16, so a 1e-12 tolerance is safe; complex64 has eps ≈ 1.2e-7 and a 1e-12 assertion will flake. Match the tolerance to the dtype.

Failure modes and how to detect them

  • Missing conjugation: ket.T @ ket returns 0 or a complex number. Detect by asserting imag ~ 0 and real ~ 1.
  • Outer product instead of inner: ket @ ket.T and np.inner(ket, ket) both return an (N,N) matrix silently. Detect by asserting the result's shape is (1,1), or use np.vdot(ket, ket), which flattens, conjugates its first argument, and always returns a scalar.
  • Shape convention: if the ket is stored as (N,), .T is a no-op and bra @ ket returns a 0-d scalar, so [0,0] raises IndexError. Detect by asserting ndim == 2 and shape[1] == 1.
  • Real-only test state: conjugation is the identity on reals, so a real test passes with the bug present. Detect by including at least one state with a nonzero imaginary component.
  • Noncomplex cast: np.array([...], dtype=float) drops imaginary parts with a ComplexWarning. Detect by asserting dtype == complex128.
  • Basis reorder: bra and ket built from different orderings give <psi|psi> != 1. The norm identity catches it.
  • Tolerance too tight for large N: rounding error grows like sqrt(N) * eps. At 2^30 amplitudes that is ~7e-12, so a fixed 1e-12 flakes. Scale the tolerance with the number of amplitudes.

Deeper detail

Two kets that differ by a global phase, |phi> = e^{i theta}|psi>, are the same physical state, so elementwise comparison is the wrong test; assert abs(<psi|phi>) ~ 1 instead. For an operator, <psi|A|psi> is real for every |psi> only when A is Hermitian: a second identity worth asserting, and it fails loudly if you conjugated on one side only. Keep the bra derived, and run the norm identity on every state you construct: one line that catches the conjugation, outer-product and reorder bugs at once.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

Represent and validate a quantum state for inner products.

Answer

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

Three things to pin down before writing code. Are these pure states or density matrices? Ket inner products are cheap; for mixed states you want the Hilbert–Schmidt inner product Tr(ρσ) or the fidelity, which is a different function. I'll assume pure states. Second, the convention: I use the physics bra-ket convention, ⟨ψ|φ⟩ = Σᵢ conj(ψᵢ)·φᵢ. Conjugate-linear in the first argument, linear in the second. That is exactly what numpy.vdot does. Third, representation: an n-qubit state is a complex128 array of length 2ⁿ, shape (2**n,), normalized so ⟨ψ|ψ⟩ = 1. I keep it 1-D rather than a column matrix so shape bugs surface instead of being flattened away.

Python
import numpy as np

def inner(psi, phi):
    psi = np.asarray(psi, dtype=np.complex128)
    phi = np.asarray(phi, dtype=np.complex128)
    if psi.ndim != 1 or phi.ndim != 1:
        raise ValueError(f"statevectors must be 1-D, got {psi.shape}, {phi.shape}")
    if psi.shape != phi.shape:
        raise ValueError(f"dimension mismatch: {psi.shape} vs {phi.shape}")
    return np.vdot(psi, phi)          # conj(psi) . phi

Trace it. Take psi = phi = [1, 1j]/√2. np.vdot gives conj(1)/√2·1/√2 + conj(1j)/√2·1j/√2 = 0.5 + (−1j)(1j)/2 = 0.5 + 0.5 = 1.0. Now drop the conjugate and use np.dot: 0.5 + (1j)(1j)/2 = 0.5 − 0.5 = 0.0. A normalized state reports itself as orthogonal to itself. That is the single most common bug in this code.

Trade-offs an interviewer will push on

Amplitude vs squared. For pure states the fidelity is F = |⟨ψ|φ⟩|², and that square is the Born-rule transition probability. Compare the amplitude when you care about distinguishability: if |⟨ψ|φ⟩| = 1e-4, the squared value is 1e-8, sitting exactly on numpy's default atol=1e-8, so the comparison is dominated by the absolute tolerance and you can no longer tell 1e-4 from 1e-5. Square only when you are reporting a probability.

Exact vs tolerance. Global phase is unobservable: |ψ⟩ and e^{iθ}|ψ⟩ are the same state, so element-wise comparison is wrong. Compare |⟨ψ|φ⟩| to 1 within a tolerance. Qiskit's Statevector.equiv does this for you (atol=1e-8 by default); Statevector.inner returns the raw ⟨ψ|φ⟩ if you want to inspect it yourself.

Failure modes, with detection

failuresymptomdetection
no conjugate (np.dot)⟨ψψ⟩ = 0 for [1, i]/√2
convention flip⟨ψφ⟩ = conj(⟨φ
shape flatteningnp.vdot ravels, so (2,2) vs (4,) passes silentlyassert ndim == 1 and shapes equal before the call
exact == 0a numerically orthogonal pair gives ~1e-16, not 0abs(ip) < 1e-8
overlap reported as probability0.9 quoted as "90%"square it: 0.81

np.vdot ravels both arguments, which is why the explicit ndim and shape checks are in the function above: without them a (2,2) array and a (4,) array of the same size compare happily.

Validation checklist

Normalize on entry: assert abs(np.vdot(psi, psi) - 1) < 1e-8. Check the self-inner-product is real and positive: a complex or negative value means the convention is flipped somewhere upstream. For orthogonality use abs(inner(psi, phi)) < 1e-8, never == 0. For equivalence use abs(inner(psi, phi)) > 1 - 1e-8, which is phase-insensitive by construction. A useful unit test: |0⟩ against (|0⟩+|1⟩)/√2 gives |⟨ψ|φ⟩| = 1/√2 ≈ 0.7071 and probability 0.5, if your code returns 0.7071 where a probability is expected, the square is missing.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

Represent and validate a quantum state for orthonormal bases.

Answer

What I'd say first. Assume a finite-dimensional pure state, amplitudes in float64, and the basis handed to me as explicit kets. Represent |ψ⟩ = Σᵢ cᵢ|eᵢ⟩ as a length-d complex vector c, with the basis as a d×k matrix B whose columns are the kets. Validation is four checks, not one: the basis is orthonormal (Gram matrix B†B = I), the basis is complete (BB† = I, i.e. k = d and it spans), the state is normalized (‖c‖ = 1), and the Born probabilities Σ|cᵢ|² = 1. The first two are separate because a single vector passes the Gram check but fails completeness.

Worked check. Take d = 2, basis {|0⟩, |1⟩}, |ψ⟩ = 0.6|0⟩ + 0.8i|1⟩.

Python
import numpy as np  # numpy 1.26, Python 3.11

def validate(basis, psi, tol=1e-10):
    d = psi.shape[0]
    assert all(v.shape == (d,) for v in basis), "wrong dimension"
    B = np.stack(basis, axis=1)              # d x k, columns are kets
    G = B.conj().T @ B                       # Gram matrix
    assert np.allclose(G, np.eye(G.shape[0]), atol=tol), "not orthonormal"
    assert np.allclose(B @ B.conj().T, np.eye(d), atol=tol), "incomplete basis"
    assert abs(np.linalg.norm(psi) - 1) < tol, "state not normalized"
    amps = B.conj().T @ psi                  # c_i = <e_i|psi>
    probs = np.abs(amps) ** 2
    assert abs(probs.sum() - 1) < tol, "probabilities do not sum to 1"
    return amps, probs

Trace: B = [[1,0],[0,1]], G = I, BB† = I, ‖ψ‖ = √(0.36+0.64) = 1. amps = [0.6, 0.8j], probs = [0.36, 0.64], sum = 1.0. Passes. Swap the basis for [e0, e0]: G = [[1,1],[1,1]], the orthonormality assert fires. Drop e1 so k = 1: G = [[1]] passes, BB† = [[1,0],[0,0]] ≠ I, the completeness assert fires. That's the check the Gram test alone misses.

Tolerance. 1e-10 is right for float64 up to d ≈ 10⁶; accumulated error grows like √d·ε with ε ≈ 2.2e-16, so at d = 2²⁰ it's ~2e-13. Past that, relax to 1e-8 rather than loosening the orthonormality gate, which is the one that catches real bugs.

Trade-offs. Dense statevector: 16 bytes per complex128 amplitude, so 20 qubits = 16 MiB, 30 qubits = 16 GiB. Fine to ~30 qubits, then it's over. Stabilizer simulation tracks thousands of qubits but only Clifford gates; a single T gate forces a statevector fallback. Sparse or tensor-network representations buy larger n at the cost of approximate amplitudes and no cheap full-basis validation. Pick dense unless the circuit is Clifford-only or n > 30.

Failure modes and how you catch them.

failuredetectioncost if missed
incomplete basisBB† ≠ I while B†B = Iprobabilities sum to <1; silent renormalization hides it
near-duplicate vectorsmax off-diagonal⟨eᵢ
non-normalized basis ketGram diagonal ≠ 1amplitudes scaled by the ket's norm
wrong dimensionlen(psi) ≠ 2ⁿindex errors or a truncated state
labels detached from vectorsprojector for label k applied to its eigenstate ≠ that statecorrect numbers, wrong qubit names

The last one is the nastiest: every numeric check passes and the answer is still wrong, so validate labels against a known eigenstate, not just the matrix.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

Represent and validate a quantum state for global phase.

Answer

Assumptions

Pure states, same Hilbert space and qubit ordering on both sides, complex128 amplitudes, and a statevector that is already normalized. If any of those is false the comparison below is the wrong tool.

Core answer

A global phase is unobservable, so a statevector is only defined up to a unit-modulus factor: |ψ⟩ and e^{iφ}|ψ⟩ are the same physical state. Represent the state as a normalized statevector, but validate it with a phase-invariant quantity (the density operator ρ = |ψ⟩⟨ψ|, or the fidelity F = |⟨ψ|φ⟩|²) never by comparing amplitudes elementwise. Elementwise comparison is what produces false test failures.

Why it works

Global phase cancels in the density operator:

(e^{iφ}|ψ⟩)(e^{iφ}|ψ⟩)† = e^{iφ}e^{-iφ}|ψ⟩⟨ψ| = |ψ⟩⟨ψ|

and in fidelity, because the modulus absorbs the unit factor:

|⟨ψ| e^{iφ}φ⟩| = |e^{iφ}| · |⟨ψ|φ⟩| = |⟨ψ|φ⟩|

Fidelity is blind to global phase and to nothing else: a relative phase error (say a stray Z) changes the state and drops F below 1, so it is still caught.

Worked check

Python
import numpy as np

psi = np.array([1, 1j]) / np.sqrt(2)      # (|0> + i|1>)/sqrt(2)
phi = np.exp(1j * 0.7) * psi              # same state, global phase 0.7

np.allclose(psi, phi)                     # elementwise -> False
overlap  = np.vdot(psi, phi)              # <psi|phi>
fidelity = abs(overlap) ** 2              # -> 1.0
phase    = np.angle(overlap)              # -> 0.7
np.allclose(np.exp(-1j * phase) * phi, psi)   # -> True

Trace: psi = [0.7071, 0.7071j]. phi = e^{0.7i}·psi = [0.5408+0.4555j, -0.4555+0.5408j]. np.allclose compares elementwise with defaults rtol=1e-5, atol=1e-8 and returns False. np.vdot(psi, phi) = conj(psi)·phi = 0.5e^{0.7i} + 0.5e^{0.7i} = e^{0.7i}, so fidelity = 1.0 and phase = 0.7. Multiplying phi by e^{-0.7i} recovers psi exactly.

Trade-offs

Fidelity is O(d), needs no phase estimate, and is the default for pass/fail tests: accept when F > 1 - 1e-8. Fit the phase explicitly with φ = arg(⟨ψ|φ⟩) only when you need the phase itself: comparing against a reference circuit's expected phase, or feeding a controlled operation. Explicit fitting is fragile: it depends on a single overlap and on a nonzero reference amplitude.

Failure modes

FailureDetection
Elementwise np.allclose on amplitudesTest fails on a correct state; switch to fidelity
Global vs relative phase confusedApply the gate; F drops below 1 - 1e-8 for relative, stays 1 for global
Phase normalized by a near-zero amplitudeGuard abs(a_k) > 1e-12 before arg; otherwise inf/nan
Numerical noise treated as exactCompare F to 1 - 1e-8, not to 1.0
Labels/bitstrings compared instead of physicsAssert on F, not on measurement strings

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Represent and validate a quantum state for relative phase.

Answer

Clarify first: relative phase is the phase between the amplitudes of a superposition. The part that survives after you factor out the unobservable global phase. For one qubit, write

|ψ⟩ = α|0⟩ + β|1⟩, with α, β complex and |α|² + |β|² = 1.

Multiplying both amplitudes by e^{iγ} changes nothing measurable. The relative phase φ = arg(β) − arg(α) does. So the representation is the pair (α, β) as complex numbers, not magnitudes plus a real "phase" field, and not a probability pair.

The canonical test state is |+φ⟩ = (|0⟩ + e^{iφ}|1⟩)/√2.

Validation. Measure in Z, then in X (apply H first). Z gives 50/50 for every φ: it cannot see phase. X gives

P(0) = |α+β|²/2 = (1 + 2·Re(α*β))/2 = (1 + cos φ)/2.

That cos φ is the interference term. A classical mixture of |0⟩ and |1⟩ with the same Z statistics gives 50/50 in X for every φ: no fringe. That contrast is the whole validation.

Python
import numpy as np  # Python 3.11, numpy 1.26

H = np.array([[1, 1], [1, -1]]) / np.sqrt(2)

def state(phi):
    return np.array([1, np.exp(1j * phi)]) / np.sqrt(2)

def probs(psi, basis):
    v = H @ psi if basis == "X" else psi
    return np.abs(v) ** 2

for phi in (0.0, np.pi / 2, np.pi):
    psi = state(phi)
    print(round(phi, 3), probs(psi, "Z").round(3), probs(psi, "X").round(3))

Trace: φ=0 → ψ=[0.707, 0.707]; Hψ=[1.0, 0.0] → Z [0.5 0.5], X [1. 0.]. φ=π/2 → ψ=[0.707, 0.707i]; Hψ=[0.5+0.5i, 0.5−0.5i] → X [0.5 0.5]. φ=π → ψ=[0.707, −0.707]; Hψ=[0, 1.414] → X [0. 1.].

0.0 [0.5 0.5] [1. 0.]
1.571 [0.5 0.5] [0.5 0.5]
3.142 [0.5 0.5] [0. 1.]

Note φ=π/2 is the ambiguous point: superposition and mixture both give 50/50. Pick φ=0 or φ=π to discriminate.

Alternatives and when to use them.

representationholds relative phasecostuse when
statevectoryes, exactly2^n complex128 = 16 bytes/amplitudepure states, n ≲ 30
density matrixyes, incl. off-diagonal ρ₀₁4^n entriesdecoherence, mixtures, purity checks
Pauli tomographyyes, reconstructed3^n measurement settingsreal hardware, not a simulator
stabilizer/Cliffordonly a discrete set of phasespoly(n)Clifford-only circuits; cannot hold arbitrary φ

Deciding criterion: if the question is "coherent or mixture?", you need off-diagonal information. Statevector, density matrix, or tomography. If only Z-basis statistics matter, a classical probability pair is enough and far cheaper.

Failure modes, with detection.

  • Phase dropped: a pipeline stores |α|, |β| only. Detect: X-basis fringe contrast should be 1 for a pure state; 0 means the phase is gone. Cost: a coherent state silently behaves as a mixture.
  • One-basis testing: only Z measured. Detect: sweep φ and check X-basis P(0) tracks (1+cos φ)/2; a flat 0.5 means phase was never tested.
  • Mixture conflation: ρ₀₁ = αβ* is nonzero for a coherent state, zero for a mixture. Detect: compute ρ₀₁ or read the X fringe.
  • Gate convention mismatch: S vs S†, or a phase gate defined as diag(1, e^{iθ}) vs diag(e^{−iθ/2}, e^{iθ/2}); the latter differs by global phase only, the former flips the sign of φ. Detect: compare against a reference statevector up to global phase, F = |⟨ψ_ref|ψ⟩|²; a sign flip shows as φ → −φ in the fringe.
  • Sign lost in serialization: JSON/CSV round-trip of complex numbers, or storing phase as a float and dropping the imaginary sign. Detect: round-trip assert |⟨ψ|ψ′⟩| = 1.

Validation is always up to global phase: never assert element-wise equality of statevectors.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

Represent and validate a quantum state for Bloch sphere.

Answer

What I'd say first

A Bloch sphere represents exactly one qubit, and only up to global phase. I write the state as

|ψ⟩ = cos(θ/2)|0⟩ + e^{iφ} sin(θ/2)|1⟩, θ ∈ [0, π], φ ∈ [0, 2π)

and the Bloch vector as r = (sinθ cosφ, sinθ sinφ, cosθ), which is exactly (Tr(ρσx), Tr(ρσy), Tr(ρσz)) with ρ = |ψ⟩⟨ψ|. I fix the convention out loud before plotting anything: Qiskit's, where |0⟩ is +z, |1⟩ is −z, |+⟩ = (|0⟩+|1⟩)/√2 is +x, and φ runs from +x toward +y. The picture is meaningless without a stated convention.

Why two parameters and not three: a normalized single-qubit statevector has two complex amplitudes, four reals, minus one for normalization, minus one for global phase. Global phase is invisible because ρ = |ψ⟩⟨ψ| is unchanged by |ψ⟩ → e^{iα}|ψ⟩, and r depends only on ρ. So θ and φ are the whole story for a pure qubit.

Validation

Compute r from ρ, check it is physical, then round-trip back to a state and compare by fidelity.

Python
import numpy as np

def bloch_from_state(psi):
    psi = np.asarray(psi, dtype=complex)
    assert abs(np.linalg.norm(psi) - 1) < 1e-9, "not normalized"
    rho = np.outer(psi, psi.conj())
    return np.array([2*rho[0,1].real, -2*rho[0,1].imag,
                     (rho[0,0]-rho[1,1]).real])

def state_from_bloch(r):
    x, y, z = r
    theta = np.arccos(np.clip(z, -1, 1))
    phi = np.arctan2(y, x)
    return np.array([np.cos(theta/2), np.exp(1j*phi)*np.sin(theta/2)])

Traced: psi = [1, 0] → r = (0, 0, 1). psi = [1/√2, 1/√2] → r = (1, 0, 0). psi = [1/√2, i/√2] → ρ[0,1] = −i/2, so r = (0, 1, 0). Round-trip (0, 1, 0) → θ = π/2, φ = π/2 → [1/√2, i/√2], fidelity 1.

The physical check is |r| ≤ 1. |r| = 1 is pure, |r| < 1 is mixed, |r| > 1 means a bug or numerical drift. A state p|0⟩⟨0| + (1−p)|1⟩⟨1| gives r = (0, 0, 2p−1); p = 0.75 → |r| = 0.5, inside the ball.

Trade-offs

representationsizemixed statesentanglementuse when
statevector2ⁿ complexnoyespure simulation, small n
density matrix4ⁿ complexyesyes, via partial tracenoise, decoherence
Bloch vector3 realsyes (r< 1)

Deciding criteria: one qubit and you want a picture → Bloch vector. Pure and many qubits → statevector. Noise or mixed → density matrix. Never a Bloch sphere for more than one qubit; take the reduced density matrix per qubit instead.

Failure modes, and how each is caught

  • θ–φ swap: θ = atan2(y, x), φ = arccos(z). Poles land on the equator. Detect by feeding |0⟩ and |1⟩ and expecting ±z.
  • Longitude sign: y = +2·Im(ρ[0,1]) instead of −2·Im(ρ[0,1]) mirrors the sphere about the xz-plane, so |+i⟩ plots at −y. Detect by checking |+i⟩.
  • Global phase retained: comparing statevectors with np.allclose instead of fidelity |⟨ψ|φ⟩|². |ψ⟩ and −|ψ⟩ differ as vectors but share a Bloch vector. Detect by comparing e^{iα}|ψ⟩.
  • Mixed state on the surface: rescaling r to unit length turns a mixed state pure. Detect by asserting |r| ≤ 1 and never renormalizing.
  • Multiple qubits compressed: a 2-qubit statevector has 4 amplitudes; you must partial-trace. A Bell state gives each qubit r = 0, the center. Detect by checking the length of psi.
  • Degrees/radians: np.cos(90) instead of np.cos(np.pi/2). Detect with a unit test on |+⟩.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

Represent and validate a quantum state for basis changes.

Answer

I'd clarify two things first: the Hilbert space is finite-dimensional and complex, and the basis is orthonormal. Then I'd answer: a quantum state is a vector |ψ> in that space; a basis change is a passive coordinate transform, not a physical operation. If the new basis is |e_j> = Σ_i U_{ij}|i>, the coordinates transform as a'j = <e_j|ψ> = Σ_i U{ij}^* a_i, i.e. a' = U† a. The state |ψ> itself is unchanged. An active operation applies a unitary V to the state: |ψ'> = V|ψ>, so coordinates in the same basis transform as a' = V a. The algebra looks similar, but passive uses U† on coordinates while active uses U on the state. For complex U, that is the conjugate transpose, not the plain transpose; U^T is only correct when U is real orthogonal.

Worked check: qubit |ψ> = 0.5|0> + (√3/2)|1>. Computational-basis probabilities are 0.25 and 0.75. Change to the X basis with H = 1/√2 [[1,1],[1,-1]]. Since H† = H, coordinates become a' = H a = [ (0.5+0.866)/1.414, (0.5-0.866)/1.414 ] = [0.966, -0.259]. Probabilities in the X basis are 0.933 and 0.067. They differ per basis state, but the total norm is 1 in both. Expectation values of a fixed observable are invariant: <Z> = 0.25 - 0.75 = -0.5 in the computational basis; in the X basis Z becomes HZH = X, and a'† X a' = 2(0.966)(-0.259) = -0.5.

Validation: check U†U = I to machine precision; check ||a|| = ||a'|| = 1; compute ρ = |ψ><ψ| in the original basis, transform it to the new basis as U† ρ U, and confirm it equals |a'><a'|. That last check catches the common mistake of comparing coordinate arrays as if they were physical states.

Failure modes and detection:

  • Active/passive confusion: you apply U to the state when you meant to change basis. Symptom: probabilities or expectation values change when only the basis should change. Detect by computing <ψ|O|ψ> for a fixed O in both representations; it must match.
  • Transpose direction: using U^T instead of U† for complex U. Detect with a complex phase, e.g. U = diag(1, i); U† = diag(1, -i), U^T = diag(1, i). The wrong one gives wrong coordinates.
  • Label mismatch: basis vectors ordered differently. Detect by checking columns of U are orthonormal and match the intended labels.
  • Nonunitary matrix: norm not preserved. Detect by computing U†U and checking max deviation from I, or by checking the norm of the transformed state.
  • Comparing coordinate arrays as physical states: two different arrays can be the same state in different bases. Detect by comparing ρ, not the arrays.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-24

Take a qubit in |psi> = alpha|0> + beta|1>. What does a measurement in the computational basis return, what state is left right after, and what changes if you measure in a rotated basis?

Answer

Lead with the Born rule and collapse, then the two things interviewers actually probe: repeatability and basis.

For |psi> = alpha|0> + beta|1> with |alpha|^2 + |beta|^2 = 1, a projective measurement in the computational basis returns 0 with probability |alpha|^2 and 1 with probability |beta|^2. The amplitudes are complex; only their moduli squared are probabilities. The two probabilities sum to one because the state is normalized: the same condition from the representation side, now read as total probability. In general p(m) = <psi|P_m|psi> = Tr(P_m rho), with P_m the projector onto outcome m.

Immediately after the outcome is recorded the superposition is gone: outcome 0 leaves |0>, outcome 1 leaves |1>, i.e. P_m|psi>/sqrt(p(m)). Collapse is not unitary and not reversible, and it is why you cannot measure one qubit twice to learn more about the original state.

Worked example. theta = pi/3, phi = 0: |psi> = (sqrt(3)/2)|0> + (1/2)|1>. So p(0) = 3/4 and p(1) = 1/4. The Bloch vector is (sin theta cos phi, sin theta sin phi, cos theta) = (0.866, 0, 0.5).

Measure the same qubit again immediately. If the first outcome was 0, the second is 0 with probability 1. Repeatability is the sharpest signal that someone understands collapse: the second measurement is not an independent 75/25 draw.

To build statistics you need a fresh preparation per shot. 1000 shots give about 750 zeros and 250 ones, with binomial standard deviation sqrt(1000 x 0.75 x 0.25) ≈ 13.7, roughly 1.4 percentage points. That is the noise floor; deviations larger than a few sigma are systematic, not luck.

Rotated basis. Measuring in X projects onto |+> = (|0>+|1>)/sqrt2 and |-> = (|0>-|1>)/sqrt2, so p(+) = |<+|psi>|^2 = (1 + x)/2 = 0.933 and p(-) = (1 - x)/2 = 0.067. Same state, different question, different distribution. On hardware you do not build a second detector: apply H, which maps |+> to |0> and |-> to |1>, then measure in Z. The relative phase phi is invisible in the computational basis and visible here.

Qiskit 1.x, AerSimulator:

python from qiskit import QuantumCircuit, transpile from qiskit.quantum_info import Statevector from qiskit_aer import AerSimulator import numpy as np

qc = QuantumCircuit(1) qc.ry(np.pi/3, 0) # theta = pi/3, phi = 0 print(Statevector(qc).probabilities()) # [0.75, 0.25]

z = qc.copy(); z.measure_all() x = qc.copy(); x.h(0); x.measure_all() # H maps the X basis onto Z

sim = AerSimulator() print(sim.run(transpile(z, sim), shots=1000).result().get_counts()) print(sim.run(transpile(x, sim), shots=1000).result().get_counts())

z ~ {'0': 750, '1': 250}; x ~ {'0': 933, '1': 67}

Failure modes worth naming. Readout is not projective in practice: superconducting readout misassigns roughly 1-3% of shots, so counts drift from |alpha|^2 even for a perfect state. Detect it by preparing |0> and |1> and building the assignment matrix. Reporting alpha or beta as a probability is the classic error. Measuring the same qubit twice inside one circuit gives correlated outcomes, not two samples. And with 100 shots, p = 0.5 carries a ±5% standard error, so small count differences are usually shot noise.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-25

Starting from |0>, walk me through a Hadamard, a phase flip on the |1> branch, then a second Hadamard: why do the amplitudes recombine to a definite |1> instead of a superposition?

Answer

Two Hadamards with a relative phase flip between them is the smallest circuit where amplitudes visibly add and cancel. Write H = (1/√2)[[1,1],[1,-1]] and track signed amplitudes, not probabilities.

stepamp of |0>amp of |1>
start10
after H1/√21/√2
after Z on |1>1/√2−1/√2
after second H(1/√2)(1/√2 − 1/√2) = 0(1/√2)(1/√2 + 1/√2) = 1

The second H sends each output amplitude to a sum of two paths, one through |0> and one through |1>. For output |0> the paths contribute +1/2 and −1/2 and cancel; for output |1> they contribute +1/2 and +1/2 and reinforce to 1. Probabilities are squared magnitudes, so P(|1>) = 1 and P(|0>) = 0. The Z gate changed no measurement probability on its own, after Z the state is still 50/50 in the computational basis, it changed a sign, and the second H converted that sign into a population difference. That conversion is interference.

Why this is not a probabilistic mixture: a 50/50 classical mixture of |0> and |1> has density matrix diag(1/2, 1/2), no off-diagonal terms. Z leaves it unchanged and the second H returns 50/50. The pure state after the first H is |+> with ρ = [[1/2, 1/2], [1/2, 1/2]]; the off-diagonal coherence is what Z flips and what the second H rotates into the diagonal. Interference is coherence being routed into a measurable population, which is why a superposition is a resource and a mixture is not.

Geometric check on the Bloch sphere: H takes |0> (+Z) to +X, Z rotates π about the Z axis to −X, and the second H takes −X to −Z, i.e. |1>. Same answer, no amplitude bookkeeping.

Qiskit 1.x:

python from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector qc = QuantumCircuit(1) qc.h(0); qc.z(0); qc.h(0) print(Statevector(qc)) # [0.+0.j, 1.+0.j]

Failure modes worth naming. If the phase flip is applied to both branches, or to |0> only, it is a global phase and nothing observable changes: the output stays 50/50. That is the most common bug: a Z on the wrong wire, or a phase gate applied before the first H or after the second H, where it does nothing useful. A simulator or noise model that keeps only populations and drops coherences reproduces the mixture and gives 50/50. On multi-qubit hardware, Qiskit's little-endian ordering puts qubit 0 at the rightmost statevector index, so flipping the wrong wire silently produces the wrong interference pattern. Detection is cheap: 1024 shots should return all 1s; a histogram near 50/50 means the relative phase never reached the second H. Before the second H, the off-diagonal of the density matrix should be −1/2, not +1/2.

The same mechanism is what Grover's diffusion operator and Deutsch–Jozsa use: an oracle writes a phase onto marked branches, and a final Hadamard layer turns that phase into a detectable amplitude.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-10

Represent and validate a quantum state for tensor products.

Answer

Core answer

Two things to pin down before writing code: the ordering convention, and whether you're storing a product state or an arbitrary composite. I'll assume the first factor varies slowest, composite index = i_A·d_B + i_B, and note that Qiskit's Statevector uses the opposite (little-endian, qubit 0 is the least significant bit). Pick one and assert it, because every downstream bug here is an index bug.

Representation: a composite of subsystems with dimensions d_A and d_B is a single vector in C^(d_A·d_B). The Kronecker product builds it: (A⊗B)[i·p + k, j·q + l] = A[i,j]·B[k,l]. Each element of A is replaced by that scalar times the whole of B: that block structure is why dimensions multiply rather than add. Two qubits give 2·2 = 4 amplitudes, with basis |00⟩, |01⟩, |10⟩, |11⟩ in index order 0..3.

Python
import numpy as np
ket0 = np.array([1, 0], dtype=complex)
ket1 = np.array([0, 1], dtype=complex)

psi = np.kron(ket0, ket1)      # |0> ⊗ |1>
print(psi)                      # [0.+0.j 1.+0.j 0.+0.j 0.+0.j]
assert psi.shape == (4,)
assert psi[0*2 + 1] == 1.0      # index = i_A*d_B + i_B

Trace: kron([1,0],[0,1]) → [1·0, 1·1, 0·0, 0·1] = [0,1,0,0]. The single 1 sits at index 1, which is |01⟩ under this convention. Reverse the factors and it lands at index 2: that is the whole failure mode in one line.

Validation, three checks:

  • Shape: psi.shape == (d_A*d_B,). Catches a flattened or outer-product result.
  • Norm: np.vdot(psi, psi) == 1 within tolerance.
  • Separability, if you claim it's a product state: reshape to d_A×d_B and check the rank is 1. A Bell state (|00⟩+|11⟩)/√2 reshapes to diag(1/√2, 1/√2), rank 2: entangled, and no Kronecker product of two single-qubit states produces it.

Trade-offs: a dense statevector is 16 bytes per amplitude (complex128), so 30 qubits ≈ 16 GiB. Fine to about 25 qubits, not beyond. Sparse storage wins when few amplitudes are nonzero (a GHZ state has 2 nonzero out of 2^n). Tensor-factorized / MPS wins for low-entanglement states, with memory scaling in the bond dimension, but don't reach for it when entanglement is volume-law; the bond dimension blows up and dense is cheaper.

Failure modes and how each is detected:

  • Factor order reversed → assert on an asymmetric product: kron(ket0, ket1) must have its 1 at index 1, not 2.
  • Tensor vs outer product → np.outer returns a 2×2 matrix; the shape assert catches it.
  • Dimensions flattened → partial trace or reshape fails; assert the composite shape.
  • Bit-string mislabeling → round-trip a known basis state through your index↔label function.
  • Density-matrix size: ρ is d×d with d = 2^n, so 4^n entries, not 2^n. Confusing Hilbert dimension with element count under-allocates by a factor of 2^n.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-12

Represent and validate a quantum state for bit ordering.

Answer

Core answer

Represent the state as a dense amplitude array plus an explicit ordering contract, and make that contract a single function rather than a habit. Three orderings are independent, and at least one pair disagrees in every major framework: the index convention (which qubit is the least-significant bit of the array index), the display convention (which qubit is leftmost in a printed ket or bitstring), and the label convention (which qubit is leftmost in a Pauli string). Fix all three in writing, then validate with a state that is not symmetric under reversal.

Why the orderings diverge

Qiskit is little-endian: qubit 0 is the least-significant bit of the statevector index. Cirq is big-endian: the first qubit in the ordering is the most-significant bit. The same physical state therefore lands at different array indices.

Python
# Qiskit 1.x — qubit 0 is the LSB of the index
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector

qc = QuantumCircuit(2)
qc.x(0)                       # X on qubit 0 only
sv = Statevector(qc)
print(sv.data)                # [0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j]

Trace: X on qubit 0 sets q0=1, q1=0. Index = q0·2⁰ + q1·2¹ = 1, so the amplitude sits at data[1].

Python
# Cirq 1.x — first qubit in the order is the MSB of the index
import cirq
q0, q1 = cirq.LineQubit.range(2)
c = cirq.Circuit(cirq.X(q0))
sv = c.final_state_vector(qubit_order=[q0, q1])
print(sv)                     # amplitude at index 2

Trace: q0=1, q1=0. Index = q0·2¹ + q1·2⁰ = 2, so the amplitude sits at sv[2]. Identical circuit, mirrored index: 1 versus 2.

Conventions table

surfaceQiskitCirq
statevector indexqubit 0 = LSBfirst qubit in order = MSB
printed ket / bitstringleftmost = highest indexleftmost = first in order
Pauli labelleftmost = highest index—

The Pauli row is the trap: in Qiskit SparsePauliOp("IX") puts X on qubit 0, because the label's leftmost character is the highest-index qubit. The opposite significance order from the index arithmetic you just used.

Validation

Use asymmetric basis states. A Bell or GHZ state is invariant under bit reversal, so it passes under both conventions and hides the bug. Prepare a single excitation, X on qubit 0 of a 2-qubit register, and assert the amplitude index. Then assert the classical side: measure_all() appends a fresh classical register, so a bitstring from a circuit that already had one concatenates registers in a defined order; check the register names and widths rather than trusting the string.

Trade-offs

Centralizing conversions in one to_canonical(state, order) function costs a copy and an indirection per boundary crossing; reversing ad hoc at each call site is cheaper to write and wrong the first time two orderings meet. The alternative that avoids the problem entirely is staying inside one framework and never crossing a serialization boundary: viable when you never cross-validate against a second simulator. Decide on two criteria: how many frameworks or formats the state crosses, and whether your tests are asymmetric. If the answer is "one" and "yes", skip the layer.

Failure modes and detection

  • Silent bit reversal: symmetric tests pass under both orderings. Detect with a single-qubit excitation at a known index.
  • Classical-register interleave: measure_all() adds a register, shifting bit positions. Detect by asserting register names and widths.
  • Hex confusion: a 4-qubit index printed as 0xA versus 0b1010. Detect by printing fixed-width binary.
  • Statevector index mismatch: comparing Qiskit and Cirq arrays elementwise without reordering. Detect by cross-checking a known asymmetric state.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13

Represent and validate a quantum state for product states.

Answer

Let me clarify the setting: a pure bipartite state |ψ⟩ in C^{d_A} ⊗ C^{d_B}, with a specified bipartition A|B. I assume a fixed computational basis and row-major index convention: basis vector |i⟩_A |j⟩_B maps to index id_B + j. The state is stored as a complex vector of length d_Ad_B.

Core answer: To validate that |ψ⟩ is a product state, reshape the amplitude vector into a d_A × d_B matrix M. Compute its singular values. If exactly one singular value is above a relative tolerance, the state is product; the corresponding left and right singular vectors give the factors |a⟩ and |b⟩. The tolerance should be tol = max(d_A, d_B) * eps * s_max, where eps = 2.22e-16 for float64 and s_max is the largest singular value. This is the same default used by numpy.linalg.matrix_rank.

Why this works: A product state |ψ⟩ = |a⟩ ⊗ |b⟩ has coefficients M[i,j] = a_i b_j, which is a rank-1 outer product. Entanglement means M has rank > 1. The singular values are the Schmidt coefficients; the Schmidt rank is the number of nonzero coefficients. Product iff Schmidt rank = 1.

Here is a runnable check in Python 3.11 with NumPy 1.26:

Python
import numpy as np

def is_product_pure(psi, dA, dB, tol=None):
    psi = np.asarray(psi, dtype=np.complex128)
    assert psi.size == dA * dB
    M = psi.reshape(dA, dB)  # row-major: index = i*dB + j
    s = np.linalg.svd(M, compute_uv=False)
    if tol is None:
        tol = max(dA, dB) * np.finfo(float).eps * s[0]
    return np.count_nonzero(s > tol) == 1, s

# |+>⊗|+> = (|00>+|01>+|10>+|11>)/2
psi_prod = np.array([0.5, 0.5, 0.5, 0.5])
print(is_product_pure(psi_prod, 2, 2))  # (True, array([1., 0.]))

# Bell state (|00>+|11>)/sqrt(2)
psi_bell = np.array([1/np.sqrt(2), 0, 0, 1/np.sqrt(2)])
print(is_product_pure(psi_bell, 2, 2))  # (False, array([0.7071, 0.7071]))

Trace: For psi_prod, M = [[0.5,0.5],[0.5,0.5]], singular values [1.0, 0.0]. tol = 2 * 2.22e-16 * 1.0 = 4.44e-16. One value above tol → product. For psi_bell, M = [[0.7071,0],[0,0.7071]], singular values [0.7071, 0.7071]. tol = 2 * 2.22e-16 * 0.7071 = 3.14e-16. Two values above tol → entangled.

Alternative: reduced-state purity. Compute ρ_A = M M†. For a normalized pure state, Tr(ρ_A^2) = sum(s_i^4). Product iff purity = 1. For psi_prod, ρ_A = [[0.5,0.5],[0.5,0.5]], purity = 1.0. For psi_bell, ρ_A = [[0.5,0],[0,0.5]], purity = 0.5. Purity avoids the SVD but only works for pure states and a fixed bipartition.

Trade-offs: SVD gives the Schmidt coefficients and the actual factors, so it is the right tool when you need to extract |a⟩ and |b⟩ or the full entanglement spectrum. Purity is a single scalar and is simpler, but it cannot distinguish product from separable mixed states. For mixed states, product means ρ_AB = ρ_A ⊗ ρ_B. Check by partial trace: compute ρ_A = Tr_B(ρ_AB), ρ_B = Tr_A(ρ_AB), then compare ρ_AB to ρ_A ⊗ ρ_B with trace distance or Frobenius norm. A separable mixed state like (|00⟩⟨00| + |11⟩⟨11|)/2 has reduced-state purity 0.5 but is not product; it is classically correlated.

Failure modes and detection:

  • Wrong reshape order: using column-major instead of row-major tests a different bipartition. A state that is product under one partition can appear entangled under another. Detect by testing a known state: Bell on qubits 1-2 tensored with |0⟩ on qubit 3 is product under (1,2)|3 but entangled under 1|(2,3). If your code reports product for the wrong partition, the reshape order is wrong.
  • Near-zero tolerance: setting tol=0 makes numerical noise produce rank > 1 for a product state. Detect by running a known product state like |00⟩; if it reports entangled, tolerance is too small.
  • Mixed-state criterion misapplied: using reduced-state purity for mixed states. Detect with the separable state above; purity < 1 but state is not entangled.
  • Partition omitted: not specifying which qubits are A and B. Detect by requiring the bipartition as an argument.
  • Classical correlation called entanglement: a separable mixed state has nonzero correlations but no entanglement. Detect by checking if the state is a convex combination of product states, or by computing a proper entanglement measure like negativity.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

Represent and validate a quantum state for exponential state size.

Answer

Clarify the question first: "represent" means pick a data structure whose size you can afford, and "validate" means prove the thing you built is the state you meant. The two are coupled: the representation decides what validation is even possible. Assume n qubits, no error correction, single node unless stated otherwise.

Representation. A general state is a vector of 2^n complex amplitudes. At complex64 (8 bytes each) that is 8·2^n bytes; complex128 doubles it.

namplitudescomplex64complex128
201.05e68 MiB16 MiB
301.07e98 GiB16 GiB
401.10e128 TiB16 TiB
501.13e158 PiB16 PiB

A density matrix is 4^n entries: at n=30 that is 8 EiB in complex64, so you never materialize one above roughly 15 qubits except for a subsystem.

So the choice follows the circuit's structure. If the circuit is Clifford, use the stabilizer formalism: Aaronson–Gottesman tracks n qubits with O(n^2) bits, so 1000 qubits is routine (CHP; Qiskit Aer's stabilizer method). If entanglement stays bounded, use a matrix product state or tensor network with bond dimension χ; memory is O(n χ^2 d). If the state is sparse, few nonzero amplitudes, use a dictionary keyed by basis index. Otherwise a dense statevector, capped by RAM: Qiskit Aer statevector, Google qsim, QuEST, or cuStateVec on GPU.

Validation. Four checks, cheapest first.

  1. Norm: sum |a_i|^2 equals 1 within 1e-10 (complex128) or 1e-5 (complex64). Catches unnormalized gates and truncation.
  2. Shape and type: assert the array is 1-D and length 2^n. This is the density-matrix-mistaken-for-statevector bug: a 4^n array passes a naive "is it square" check.
  3. Cross-simulator: run the same circuit on two backends (Aer statevector vs MPS with large χ) and compare fidelities; disagreement above 1e-6 means truncation or a gate bug.
  4. Sampling: draw 10^5 shots and compare the empirical distribution to |a_i|^2 with a chi-square or total-variation test. Catches phase errors that the norm misses.

Failure modes and how you see them. Memory exhaustion is predictable, not surprising: precompute 8·2^n and compare to available RAM before allocating. A 32-qubit complex128 run needs 64 GiB and dies on a 32 GiB box. Hidden copies come from simulator APIs that return a copy, doubling peak memory; detect with tracemalloc or peak RSS, where a 2× spike over the state size means a copy. Accelerator limits bite the same way: an A100 has 40 or 80 GiB, and a 33-qubit complex64 state is 64 GiB, so check nvidia-smi before launch, not after. MPS truncation at high entanglement is the subtle one: bond dimension χ caps how much entanglement you can hold, so sweep χ (64, 128, 256) and check that the observable converges; if it does not, the state is not low-entanglement and MPS is the wrong tool. Finally, "read all amplitudes" is not a validation strategy: you cannot print 2^30 numbers, so validate by sampling and by comparing a few indexed amplitudes against a small-n exact run.

The one-liner: pick the representation from the circuit's structure (Clifford → stabilizer, low entanglement → MPS, else dense), size it with 8·2^n bytes, and validate with norm, shape, cross-backend, and sampling.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Represent and validate a quantum state for pure states.

Answer

For a pure state I represent it as a normalized ket |ψ⟩ and, when I need to validate it or pass it through a noisy pipeline, as the rank-1 density matrix ρ = |ψ⟩⟨ψ|. The validation is: ρ is Hermitian, Tr(ρ)=1, rank(ρ)=1, ρ²=ρ, and the off-diagonal entries match the expected coherences. The ket alone is enough for a closed unitary simulation; the density matrix is what you validate when the state may have been prepared imperfectly or you need to compare against a measured ρ.

Concrete check. Take |ψ⟩ = (|0⟩ + i|1⟩)/√2. Then ρ = ½[[1, -i],[i, 1]]. Python 3.11 with NumPy 1.26:

Python
import numpy as np
psi = np.array([1, 1j]) / np.sqrt(2)
rho = np.outer(psi, psi.conj())          # [[0.5, -0.5j], [0.5j, 0.5]]
assert np.allclose(rho, rho.conj().T, atol=1e-8)   # Hermitian
assert np.isclose(np.trace(rho), 1.0, atol=1e-8)   # trace 1
assert np.linalg.matrix_rank(rho, tol=1e-8) == 1   # rank 1
assert np.allclose(rho @ rho, rho, atol=1e-8)      # pure: ρ² = ρ
assert np.allclose(rho[0, 1], -0.5j, atol=1e-8)    # expected coherence

Why these follow. Tr(|ψ⟩⟨ψ|) = ⟨ψ|ψ⟩ = 1, so trace-one is normalization. The outer product of a vector with itself has one nonzero eigenvalue, |⟨ψ|ψ⟩|², so rank one separates pure from mixed. Global phase cancels: (e^{iφ}|ψ⟩)(e^{iφ}|ψ⟩)† = |ψ⟩⟨ψ|, so validation must compare ρ, not kets.

Alternatives and when to pick them:

representationsize for n qubitsmixed/noisedeciding criterion
state vector2^n complex amplitudesnoclosed, pure, unitary-only simulation
density matrix4^n complex entriesyesopen system, decoherence, measured state
stabilizerO(n²) bitsno (pure Clifford)many qubits, Clifford gates only

For 20 qubits, a state vector is 2^20 ≈ 1M amplitudes (16 MB complex128); a density matrix is 4^20 ≈ 1.1e12 entries (about 17 TB), so you only materialize ρ for small n or when noise forces it. Stabilizer is the right call for 1000-qubit Clifford circuits, but it cannot represent a general pure state like the example above once you leave the Clifford group.

Failure modes and detection:

  • Ordinary transpose instead of conjugate transpose. For ρ with imaginary coherences, ρ^T flips the sign of the off-diagonal and fails the Hermiticity check. Detect with np.allclose(rho, rho.conj().T).
  • Unnormalized ket. Trace is not 1; detect with np.trace(rho) and compare to 1 within atol=1e-8 for double precision.
  • Elementwise square. |ψ_i|² gives probabilities and zeroes the off-diagonal, so rank becomes >1 or the coherence check fails. Detect by comparing rho[0,1] to the expected -i/2.
  • Precision asymmetry. A tolerance tighter than machine epsilon rejects valid states; a loose tolerance accepts a mixed state as pure. Use atol=1e-8 for float64 and scale with the norm of ρ.
  • Row-vector confusion. Computing ⟨ψ|ψ⟩ gives a scalar, not a matrix; detect by asserting rho.shape == (2,2) for one qubit.
  • Global phase. |ψ⟩ and e^{iφ}|ψ⟩ produce the same ρ; a validator that compares kets will flag a false failure. Compare ρ.

Decision point: if the state is closed and you only apply unitaries, keep the ket and validate normalization. If you need to model decoherence, compare to tomography, or compute measurement probabilities under noise, build ρ and run the four checks above. If the circuit is Clifford and n is large, use the stabilizer representation and validate the stabilizer generators instead.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-16

Represent and validate a quantum state for mixed states.

Answer

What I'd say first

Assume a finite-dimensional system (n qubits, so d = 2ⁿ) and that I either know the preparation procedure or have tomographic data. The state is a density matrix ρ on C^d: Hermitian, positive semidefinite, trace 1. Those three properties are not stylistic. They are exactly what makes Tr(ρE) a probability for every POVM element E, so PSD is the one that carries the physics. Purity, entropy and Bloch coordinates are all derived from ρ.

Representation

ρ = Σᵢ pᵢ|ψᵢ⟩⟨ψᵢ|, pᵢ ≥ 0, Σpᵢ = 1. One qubit: ρ = (I + r·σ)/2 with Bloch vector r, |r| ≤ 1. |r| = 1 is pure, |r| < 1 is mixed, r = 0 is maximally mixed. The valid set is the Bloch ball; its surface is the pure states.

Validation

Three invariants decide it: Hermitian, trace 1, eigenvalues ≥ 0. Purity Tr(ρ²) then lands in [1/d, 1].

Python
import numpy as np

def validate(rho, tol=1e-9):
    rho = np.asarray(rho, dtype=complex)
    assert rho.ndim == 2 and rho.shape[0] == rho.shape[1]
    assert np.allclose(rho, rho.conj().T, atol=tol), "not Hermitian"
    tr = np.trace(rho)
    assert abs(tr - 1) < tol, f"trace={tr}"
    ev = np.linalg.eigvalsh(rho)          # Hermitian -> real eigenvalues, O(d^3)
    assert ev.min() > -tol, f"min eigenvalue={ev.min()}"
    return float(np.real(np.trace(rho @ rho)))   # purity

Trace it. ρ = I/2 = [[.5,0],[0,.5]]: Hermitian, trace 1.0, eigenvalues [.5,.5], min .5 > -tol, ρ@ρ = I/4, trace 0.5 → returns 0.5. ρ = |+⟩⟨+| = [[.5,.5],[.5,.5]]: eigenvalues [0,1], min 0 > -tol, ρ@ρ = ρ (a projector), trace 1.0 → returns 1.0.

Two practical notes. First, eigvalsh is O(d³); at d = 2²⁰ you cannot run it, so this is a small-d tool. For large systems you check what you can (Hermitian, trace, Tr(ρ²) ≤ 1) and sample ⟨ψ|ρ|ψ⟩ ≥ 0 on random ψ, which is necessary but not sufficient. Second, scale tol with d: LAPACK's eigenvalue error is O(d·ε·‖ρ‖₂), so a fixed 1e-9 is fine at d = 2 and marginal by d ≈ 2²⁰.

When validation fails

Tomographic linear inversion routinely returns a matrix with small negative eigenvalues. Don't throw it away: project onto the PSD cone: eigendecompose, clip negative eigenvalues to 0, renormalize the trace. That is the cheap version of the maximum-likelihood estimate QST packages use; MLE enforces positivity by construction, linear inversion does not.

Ensemble ambiguity

I/2 = ½|0⟩⟨0| + ½|1⟩⟨1| = ½|+⟩⟨+| + ½|−⟩⟨−|. Same ρ, different decompositions, identical predictions for every observable. The decomposition is not part of the state.

Mixture vs superposition

|+⟩⟨+| has off-diagonal ½; the mixture ½|0⟩⟨0| + ½|1⟩⟨1| = I/2 has zero off-diagonals. ⟨X⟩ = 1 versus 0. Coherence is the discriminator.

Reduced states

Bell |Φ⁺⟩ = (|00⟩+|11⟩)/√2; partial trace over one qubit gives I/2, purity 0.5. Entanglement shows up as a mixed subsystem.

Python
def partial_trace(rho, d, keep):
    t = rho.reshape(d, d, d, d)   # t[i,j,k,l] = rho[i*d+j, k*d+l]
    return np.einsum('ijkj->ik', t) if keep == 0 else np.einsum('ijil->jl', t)

For |Φ⁺⟩, partial_trace(rho, 2, 0) returns [[.5,0],[0,.5]].

Trade-offs

state vectordensity matrix
entries2ⁿ4ⁿ
n = 20~1M~1T
memory (complex128)~16 MB~16 TiB
closed systemyesyes
discarded subsystem / decoherencenoyes

Use a state vector when the system is closed and no subsystem is discarded; use ρ when there is preparation uncertainty, decoherence, or you need a reduced state. The 4ⁿ wall is memory: 16·4ⁿ bytes, so n = 12 is 268 MB, n = 13 is 1.07 GB, n = 14 is 4.3 GB. A laptop tops out near n = 13–14 for storage, earlier for anything O(d³).

Failure modes

  • Decomposition treated as unique: reconstruct ρ from two different ensembles and compare, if code stores the ensemble as ground truth it reports unobservable structure.
  • Mixture confused with superposition: check off-diagonals or ⟨X⟩; a fully decohered qubit has ⟨X⟩ = 0.
  • Purity ignored: compute Tr(ρ²); a depolarized qubit with p = 0.3 has purity 1 − p + p²/2 = 0.745, not 1.
  • Noise model unversioned: store the channel parameters (p, T1, T2) alongside ρ, or the state cannot be reproduced.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-17

Represent and validate a quantum state for trace.

Answer

The 90-second answer

Two decisions: which object holds the state, and which invariants you assert on it.

A pure state is a statevector: a complex vector of length 2^n with Σ|a_i|² = 1. A mixed state, or anything carrying noise or a measurement record, is a density matrix ρ: 2^n × 2^n, Hermitian, positive semidefinite, Tr(ρ) = 1. The trace is total probability. It is 1 for any valid state and it is basis-independent, because Tr(UρU†) = Tr(ρ) for unitary U.

Validation is a fixed assertion list, cheapest first: shape is a power of two, dtype is complex, every entry finite, then the state-specific invariants. Norm ≈ 1 for a statevector; Hermitian, trace ≈ 1, min eigenvalue ≥ 0 for a density matrix. Tolerance 1e-8 in float64.

Python
import numpy as np

def validate(psi=None, rho=None, atol=1e-8):
    if psi is not None:
        psi = np.asarray(psi, dtype=complex)
        assert psi.ndim == 1 and (psi.size & (psi.size - 1)) == 0, "length not a power of two"
        assert np.all(np.isfinite(psi)), "non-finite amplitude"
        n = np.linalg.norm(psi)
        assert abs(n - 1.0) < atol, f"norm {n} != 1"
        return psi.size.bit_length() - 1
    rho = np.asarray(rho, dtype=complex)
    assert rho.ndim == 2, "density matrix must be 2-D"
    d = rho.shape[0]
    assert rho.shape == (d, d) and (d & (d - 1)) == 0, "not a power-of-two square"
    assert np.all(np.isfinite(rho)), "non-finite entry"
    assert np.allclose(rho, rho.conj().T, atol=atol), "not Hermitian"
    tr = np.trace(rho)
    assert abs(tr - 1.0) < atol, f"trace {tr} != 1"
    ev = np.linalg.eigvalsh(rho)
    assert ev.min() > -atol, f"not PSD, min eigenvalue {ev.min()}"
    return d.bit_length() - 1

Trace it on psi = [1, 1j]/√2: norm = √(0.5 + 0.5) = 1.0, passes, returns 1. ρ = np.outer(psi, psi.conj()) = [[0.5, -0.5j], [0.5j, 0.5]]; trace = 1.0, eigenvalues {1, 0}, min = 0 ≥ -1e-8, passes.

Statevector vs density matrix

statevectordensity matrix
memory (complex128)2^n × 16 B4^n × 16 B
n = 2016 MiB16 TiB
n = 3016 GiB—
mixed states / noisenoyes
reduced state of a subsystempartial tracepartial trace

Deciding rule: unitary circuit, no noise, n above ~25 → statevector. Noise, mid-circuit measurement with feedback, or a subsystem's reduced state → density matrix, and accept the 2^n → 4^n blowup, which caps you near n = 15 on one node.

Trace-preserving operations and where trace breaks

Unitary evolution preserves trace exactly in exact arithmetic: Tr(UρU†) = Tr(ρ). Measurement is where it breaks. A Kraus operator K_0 = |0⟩⟨0| applied to ρ = [[0.5, -0.5j], [0.5j, 0.5]] gives ρ' = K_0 ρ K_0† = [[0.5, 0], [0, 0]], trace 0.5: that is the outcome probability p_0, not a bug. The post-measurement state is ρ'/p_0 = |0⟩⟨0|, trace 1. Forgetting the division leaves trace = p_0, and every downstream probability is scaled by p_0.

Failure modes and detection

  • Numeric drift: repeated matmuls accumulate rounding. float64 eps is 2.2e-16; worst-case trace error grows ~linearly in the number of operations, so 10^6 gates lands near 1e-10: inside a 1e-8 tolerance, but a 1e-12 tolerance would false-alarm. Detect by asserting trace after each layer, not only at the end.
  • Unnormalized measurement branch: trace = p_0 ≠ 1; the trace assertion fires. Symptom downstream: probabilities sum to p_0.
  • Wrong shape / partial matrix: a density matrix built from the diagonal only, or a statevector reshaped with the wrong axis order. Qiskit is little-endian (qubit 0 is the least significant bit); NumPy reshape is row-major. Detect with a known-state test: prepare |00⟩, assert index 0 is 1.
  • Trace of a statevector requested: type confusion; a statevector has no trace. Form ρ = np.outer(psi, psi.conj()) or wrap in DensityMatrix.

Libraries: Qiskit's Statevector.is_valid() and DensityMatrix.is_valid() run exactly these checks; QuTiP's Qobj exposes .tr(), .isherm and .unit().

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15

Represent and validate a quantum state for density validity.

Answer

What a strong candidate says first

A density matrix is a d×d complex matrix, d = 2^n, and "valid" means exactly three things: Hermitian, trace 1, positive semidefinite. Rank, off-diagonal structure and entanglement all follow from those. Represent it as a dense complex128 array while d ≤ 4096 (12 qubits, 268 MB); past that, represent it as an ensemble {(p_k, |ψ_k⟩)} so PSD holds by construction and you validate the weights instead of the matrix.

Validate cheapest-first: shape, Hermiticity, trace, then eigenvalues. The first three are O(d²); the eigenvalue check is O(d³) and is the only one that catches a negative population.

Python
import numpy as np  # numpy 1.26, Python 3.11

def validate_density(rho, n_qubits, tol=1e-9):
    d = 2 ** n_qubits
    assert rho.shape == (d, d), f"shape {rho.shape} != {(d, d)}"
    rho = np.asarray(rho, dtype=np.complex128)

    herm = np.max(np.abs(rho - rho.conj().T))
    if herm > tol:
        raise ValueError(f"not Hermitian: max|rho - rho^H| = {herm:.3e}")

    tr = np.trace(rho).real
    if abs(tr - 1.0) > tol:
        raise ValueError(f"trace = {tr:.12f}, off by {abs(tr - 1):.3e}")

    # eigvalsh reads only the lower triangle. Hermiticity is already
    # verified to within tol, and Weyl bounds the eigenvalue shift by herm.
    evals = np.linalg.eigvalsh(rho)
    if evals.min() < -tol:
        raise ValueError(f"min eigenvalue = {evals.min():.3e} < -{tol:.0e}")
    return evals

Worked trace: a state that passes trace and Hermiticity and is still not physical

Werner state, p = 1.05:

Python
phi = np.zeros(4); phi[0] = phi[3] = 1 / np.sqrt(2)   # |Phi+>
rho = 1.05 * np.outer(phi, phi) + (1 - 1.05) * np.eye(4) / 4

Trace = 1.05·1 + (−0.05)·(4/4) = 1.0 exactly. Hermiticity error = 0. Eigenvalues: (1+3p)/4 = 1.0375 once, (1−p)/4 = −0.0125 three times. The trace check passes, the Hermiticity check passes, and eigvalsh returns min = −0.0125 < −1e-9, so the validator rejects. A trace-only validator ships a state with a 1.25% negative population.

Failure modes, detection, cost

failuredetectioncost if missed
negative eigenvalue hiddeneigvalsh(rho).min() < -tolexpectation values outside the physical range; 1.25% negative population above
trace normalized silently (rho /= np.trace(rho))assert trace before normalizing; log the raw tracehides Σ K†K ≠ I: a raw trace of 1.1 becomes a plausible-looking state
entrywise positivity (rho >= 0).all()false-rejects−⟩⟨−
non-square / wrong drho.shape == (2**n, 2**n)index errors or silent broadcasting
basis metadata missingcarry n_qubits and the qubit-ordering convention with the arraya valid ρ for the wrong qubit order (Qiskit is little-endian: qubit 0 is the least significant bit)
tolerance too looserequire tol ≤ 1e-9 for float64tol = 1e-2 accepts the −0.0125 above

Symmetrizing (ρ + ρ†)/2 is a repair, not a check: if ‖ρ − ρ†‖ = 1e-3, the repaired state is 1e-3 away from what was computed. Log the correction norm and treat anything above tol as a construction bug.

Trade-offs and when not to use the dense path

  • Dense ρ: exact spectrum, O(d²) memory, O(d³) validation. d = 1024 is 16.8 MB and eigvalsh takes roughly 0.1 s on one core; d = 4096 is 268 MB and 64× slower. Ceiling is around 12 qubits.
  • Ensemble {(p_k, |ψ_k⟩)}: PSD is free, memory O(k·d), but you cannot read ρ_ij without forming ρ. Validate p_k ≥ 0 and Σp_k = 1 in O(k).
  • MPO / tensor network: O(n χ³) memory, but no cheap PSD test. Contracting to dense defeats the purpose.
  • Cholesky (ρ + εI = LL†) instead of eigvalsh: ~3× cheaper, succeeds iff min eval ≥ −ε, but returns a boolean rather than the offending eigenvalue. Gate with Cholesky, diagnose with eigvalsh.
  • Randomized screening ⟨ψ|ρ|ψ⟩ ≥ 0: O(d²) per sample, necessary but not sufficient. Catches gross violations, never certifies.

One trap: PSD of ρ is not PSD of the partial transpose. ρ^{T_A} has a negative eigenvalue for a valid entangled state (Werner at p > 1/3). That is an entanglement test, not a validity test.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Represent and validate a quantum state for purity.

Answer

Core answer. Represent the state as a density matrix ρ: a d×d complex matrix, Hermitian, positive semidefinite, trace 1, where d is the Hilbert-space dimension. Purity is Tr(ρ²). It equals 1 exactly for a pure state and 1/d for the maximally mixed state, so the valid range is [1/d, 1]. Validation is four checks: Hermitian within tolerance, trace ≈ 1, all eigenvalues ≥ 0, and purity inside [1/d, 1]. Report d and the tolerance you used, because both bound what "valid" means.

Why Tr(ρ²). Write ρ in its eigenbasis: ρ = Σ pᵢ |i⟩⟨i| with pᵢ ≥ 0, Σ pᵢ = 1. Then ρ² = Σ pᵢ² |i⟩⟨i| and Tr(ρ²) = Σ pᵢ². Purity is the sum of squared eigenvalues: a concentration measure on the spectrum. One eigenvalue at 1 gives 1; uniform pᵢ = 1/d gives d·(1/d²) = 1/d. That is why the lower bound is 1/d and not 0.

Worked check. Take the pure state |+⟩ = (|0⟩+|1⟩)/√2, ρ = [[0.5, 0.5], [0.5, 0.5]]. ρ² = ρ (idempotent), Tr = 1.0 → pure. Now diag(0.7, 0.3): Tr(ρ²) = 0.49 + 0.09 = 0.58, inside [0.5, 1] → mixed. The elementwise square of the first matrix is [[0.25, 0.25], [0.25, 0.25]], trace 0.5: wrong by half. Purity is a matrix product, never elementwise.

Python
import numpy as np

def validate(rho, tol=1e-9):
    d = rho.shape[0]
    herm_err = np.max(np.abs(rho - rho.conj().T))
    trace = np.trace(rho).real
    evals = np.linalg.eigvalsh(rho)      # Hermitian input
    purity = float(np.sum(evals**2))     # == Tr(rho @ rho)
    return dict(d=d, herm_err=herm_err, trace=trace,
                min_eval=float(evals.min()), purity=purity,
                lower=1.0/d, ok=(herm_err < tol and abs(trace - 1) < tol
                                 and evals.min() > -tol
                                 and 1.0/d - tol <= purity <= 1.0 + tol))

Trace: validate(np.array([[0.5, 0.5], [0.5, 0.5]])) → purity 1.0, ok True. validate(np.diag([0.7, 0.3])) → purity 0.58, ok True. validate(np.diag([0.6, 0.6])) → trace 1.2, ok False.

Trade-offs. Two ways to get purity: Tr(ρ@ρ) is O(d³) and needs no eigen-decomposition; eigvalsh is also O(d³) but hands you the spectrum, so you get the PSD check and purity in one pass. Prefer it when d is small enough to diagonalize. For large d (say d > 10⁴) diagonalization is too slow; use Hutchinson: Tr(ρ²) ≈ (1/m) Σ zᵢ† ρ² zᵢ with random ±1 vectors, O(m d²) per estimate, unbiased with variance scaling as 1/m. Fine for monitoring, not for a pass/fail gate.

Failure modes. Elementwise square instead of matrix product: detect by comparing against Tr(ρ@ρ) on a non-diagonal test state. Purity above 1 from float rounding on a near-pure state: clip or widen tolerance, don't report 1.0000001 as a bug. Ignoring the 1/d bound: a "purity 0.4" on a qubit is impossible; flag it. Subsystem confusion: a reduced state's purity below 1 means entanglement with the traced-out part, not experimental noise; check by computing purity of the full state. Calling purity entropy: entropy is -Tr(ρ log ρ), 0 for pure and log d for maximally mixed; they move in opposite directions.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-20

Represent and validate a quantum state for mixture versus superposition.

Answer

Clarify first. "Represent" means write the state as a density matrix ρ, not a ket: a mixture has no ket. "Validate" means run a measurement whose outcome statistics differ between the two candidates. I'll assume one qubit, ideal projective measurements, and many prepared copies; without repetition you can't validate anything statistical.

Core answer. Take the standard trap pair:

  • Proper mixture: ρ_mix = ½|0⟩⟨0| + ½|1⟩⟨1| = [[½, 0], [0, ½]] = I/2.
  • Coherent superposition: ρ_+ = |+⟩⟨+| = ½(|0⟩+|1⟩)(⟨0|+⟨1|) = [[½, ½], [½, ½]].

Identical diagonals, so a Z-basis measurement gives 0 with probability ½ and 1 with probability ½ in both cases. The difference lives entirely in the off-diagonal coherence: 0 for the mixture, ½ for the superposition. That is the whole answer. A mixture is diagonal in the basis where the ensemble members are definite; a superposition carries off-diagonal terms, and those terms are what a measurement in a conjugate basis detects.

Worked check. Measure in the X basis, |±⟩ = (|0⟩ ± |1⟩)/√2. Born rule: P(+) = ⟨+|ρ|+⟩ = ½(ρ₀₀ + ρ₀₁ + ρ₁₀ + ρ₁₁).

  • ρ_mix: ½(½ + 0 + 0 + ½) = ½. A coin flip.
  • ρ_+: ½(½ + ½ + ½ + ½) = 1. Always +.

One X-basis shot on |+⟩ returns + with certainty; the mixture returns + half the time. In Bloch terms ρ = (I + r·σ)/2: the mixture has r = 0, the superposition r = (1, 0, 0). Purity Tr(ρ²) = (1 + |r|²)/2 is ½ versus 1.

Finite shots. You never observe exactly ½. With n X-basis shots on the mixture the + count is Binomial(n, ½). At n = 20, seeing all 20 + has probability 2⁻²⁰ ≈ 9.5×10⁻⁷ under the mixture: decisive. Seeing 11/20 + has probability ≈ 0.16, which is noise; don't call coherence on that.

Alternatives, and when to use them. A single X-basis measurement is the cheapest decisive test for this pair. Full one-qubit tomography (measure X, Y, Z, reconstruct ρ) costs roughly 3× the shots but returns the whole matrix and catches phase errors the X test alone misses. A purity estimate via randomized measurements or a swap test gives Tr(ρ²) without reconstructing ρ: useful when you only need "pure or mixed". If your protocol only ever reads the computational basis, say a Z-basis sampling task, the distinction is operationally invisible and spending shots on X is waste.

Failure modes, with detection.

  1. One-basis conclusion: measuring only Z and declaring "it's a mixture". Detect by running the X test; any P(+) above ½ beyond error bars means coherence.
  2. Treating the diagonal as basis-independent: the diagonal entries of ρ depend on the basis. In the X basis ρ_mix still has diagonal (½, ½) but ρ_+ has (1, 0). Detect by computing the diagonal in the basis you actually measure, or by checking Tr(ρ²).
  3. Ignoring phase noise: a drifting relative phase φ gives ρ = [[½, e^{iφ}/2], [e^{-iφ}/2, ½]] and P(+) = ½(1 + cos φ). At φ = π it is |−⟩, P(+) = 0. Detect by measuring P(+) in more than one basis or tracking it over time; a slow decay of the X-basis bias is dephasing.
  4. Overreading finite shots: 11/20 is consistent with ½. Detect with a binomial confidence interval before claiming coherence.
  5. Hidden-variable story: assuming the superposition is just classical ignorance about |0⟩ versus |1⟩. That is exactly the mixture, and it predicts P(+) = ½. The deterministic + outcome kills it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-19

Represent and validate a quantum state for partial trace.

Answer

What a strong candidate says first

Partial trace is the unique map that turns a joint state on A⊗B into the operator on A that reproduces every local measurement: rho_A satisfies Tr(rho_A O_A) = Tr(rho_AB (O_A ⊗ I_B)) for every observable O_A on A. Nothing else on A does.

Representation: hold the joint state as a density matrix. From a statevector psi, rho_AB = |psi><psi|. Reshape rho_AB into a 4-index tensor ordered (A_out, B_out, A_in, B_in) and contract the two B axes. That is the whole algorithm: the reshape is where the bugs live, because the axis order has to match the library's qubit ordering.

Worked code and trace

Python
import numpy as np
from qiskit.quantum_info import Statevector, partial_trace

# Qiskit 1.x is little-endian: index = q_{n-1} ... q_1 q_0, qubit 0 is the rightmost factor.
psi = Statevector([1/np.sqrt(2), 0, 0, 1/np.sqrt(2)])   # (|00> + |11>)/sqrt(2)

rho = np.outer(psi.data, psi.data.conj()).reshape(2, 2, 2, 2)  # (q1_out, q0_out, q1_in, q0_in)
rho0 = np.trace(rho, axis1=0, axis2=2)                          # trace out qubit 1 -> qubit 0

print(np.allclose(rho0, partial_trace(psi, [1]).data))  # True
print(np.round(rho0, 3))
# [[0.5 0. ]
#  [0.  0.5]]
print(np.trace(rho0).real, np.linalg.eigvalsh(rho0), np.trace(rho0 @ rho0).real)
# 1.0 [0.5 0.5] 0.5

Trace it by hand: rho_AB has 0.5 at (0,0,0,0), (0,0,1,1), (1,1,0,0), (1,1,1,1). Summing over q1_out = q1_in leaves 0.5 on the diagonal of qubit 0 and zero off-diagonal: I/2. Trace 1, eigenvalues 0.5/0.5, purity 0.5. The Bell state is maximally entangled, so its marginals are maximally mixed.

Validation checklist

  • Tr(rho_A) = 1 to ~1e-10.
  • Hermitian: np.allclose(rho_A, rho_A.conj().T).
  • PSD: min eigenvalue ≥ -1e-10 (clip numerical noise).
  • Purity Tr(rho_A²) in [1/d, 1]; 1 means pure, 1/d means maximally mixed.
  • Cross-check against qiskit.quantum_info.partial_trace or an independent einsum.

Alternatives and when to use them

methodcostuse when
dense rho + reshape/trace16·4^n bytesn ≤ ~12 (n=12 → 268 MB)
Schmidt/SVD of psi reshaped to (2^k, 2^(n-k))16·2^n bytespure states; also gives entanglement entropy
local Pauli tomography (3^n settings)O(n) memoryreal hardware, n small
MPS / tensor networkbond-dim dependentn ≥ 20, low entanglement

For a pure state the SVD route is strictly better: singular values s_i give rho_A = diag(s_i²) in the right basis, and S = -Σ s_i² log s_i². Bell state: s = (1/√2, 1/√2), S = 1 bit. Dense rho at n=20 is 4^20 ≈ 1.1e12 complex128 ≈ 17.6 TB, not an option.

Failure modes

  • Wrong axis order. Qiskit is little-endian; textbook derivations are often big-endian. Test with an asymmetric product state, not a Bell state: Bell is symmetric and hides the bug. psi = [1/√2, 1/√2, 0, 0] is |0>_1 ⊗ |+>_0; tracing out qubit 1 must give |+><+| = 0.5[[1,1],[1,1]], and tracing out qubit 0 gives [[1,0],[0,0]]. If you get the latter, your axes are swapped.
  • Slicing the statevector instead of tracing. psi[0:2] for the Bell state is [1/√2, 0], norm 0.5, not a state. Reduced states of entangled systems are mixed; you must form rho_AB first.
  • Assuming the reduced state is pure. Bell → I/2, purity 0.5. Asserting purity turns entanglement into a false "noise" report.
  • Reading the trace-out as information loss. rho_A is a coarse-graining: it reproduces local statistics exactly and contains none of the A–B correlations. That is the definition, not a bug.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-21

Represent and validate a quantum state for no cloning.

Answer

What I'd say first. No-cloning is a statement about unknown quantum states, not about data. If the state is known, you hold a classical preparation instruction, you can prepare as many copies as you like, and classical bits copy for free. The theorem bites only when the state is unknown to the copier. So before validating anything, I'd pin down which of the two a vendor is claiming, and I'd assume the copier is not allowed to know the basis unless told otherwise.

The mechanism, in three lines of algebra. Suppose a unitary U copies two states: U|ψ⟩|0⟩ = |ψ⟩|ψ⟩ and U|φ⟩|0⟩ = |φ⟩|φ⟩. Unitarity preserves inner products, so ⟨ψ|φ⟩ = ⟨ψ|φ⟩². That forces ⟨ψ|φ⟩ ∈ {0, 1}: only orthogonal states, or identical ones, can be copied. Any two nonorthogonal states (the four BB84 states, pairwise overlap 1/√2) cannot both be cloned by one device. I'd write that on the board before discussing anything else.

What the alternatives actually cost.

approachwhat it doesfidelity / cost
exact cloning of orthogonal statesallowedF = 1, but only if the copier knows the basis
universal 1→2 cloning (Bužek–Hillery)clones any qubit equally badlyF = 5/6 ≈ 0.833; 1→N is (2N+1)/(3N)
phase-covariant cloningoptimal for equatorial states such as BB84F = (1 + 1/√2)/2 ≈ 0.854
measure-and-repreparemeasure in a guessed basis, re-prepareF = 1 in the right basis, 1/2 in the wrong one; 0.75 averaged over BB84 bases
probabilistic cloning (Duan–Guo)exact copies with probability pp = 1/(1+s) for overlap s; ≈ 0.586 for BB84 states
teleportationmoves a state, destroys the original1 ebit + 2 classical bits
quantum error correctionprotects a state without copying itspreads entanglement across a code block

The deciding criterion is whether the copier may know the basis. If it may, cloning is trivial and the theorem is irrelevant. If it may not, 0.854 is the ceiling for BB84 states, and anything above it is either cheating or not quantum.

How I'd validate a claim. Represent the state as a density matrix ρ and compare it with the target σ using fidelity F(ρ,σ) = (tr√(√ρ σ √ρ))². Then run the device blind: choose the basis after the device has acted, so it cannot know which states it is cloning. Prepare BB84 states, send one copy through, measure both outputs in the same basis, and estimate fidelity. A device that measures and reprepares lands near 0.75; a genuine phase-covariant cloner tops out at 0.854; a claimed F = 1 on nonorthogonal states is a red flag. Check the device's ancilla too: no-cloning forbids copying, but it does not forbid entangling the output with the device, and that breaks security just as badly. A Bell-type test on the ancilla catches it.

Failure modes and how I'd catch them.

  • "We can't copy your key", if the key is classical bits, this is false. Ask whether the input is a bitstring or a quantum state.
  • Measurement plus reprepare sold as cloning: fidelity lands near 0.75 on BB84 states, below the 0.854 bound.
  • Probabilistic cloning with the success probability hidden: demand p and the failure flag; for BB84 states p ≤ 0.586.
  • No-cloning quoted as the whole security proof: it rules out one attack class, not detector side channels or entanglement attacks. Ask for the threat model.
  • Global phase treated as a difference — |ψ⟩ and e^{iθ}|ψ⟩ are the same state. Compare density matrices, not vectors.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Represent and validate a quantum state for state tomography.

Answer

First I'd pin down three things: how many qubits, how many copies I can prepare, and what precision the downstream task needs. Take a 3-qubit state I can prepare on demand: the usual lab setting.

Representation. The state is a density matrix ρ: a 2^N × 2^N Hermitian, positive-semidefinite, unit-trace matrix. For N=3 that's 8×8 with 4^N − 1 = 63 real parameters. I don't carry the raw matrix during estimation; I carry the Pauli expectation values ⟨P⟩ over all 4^N Pauli operators, because ρ = (1/2^N) Σ_P ⟨P⟩ P. Those 63 numbers are the state.

Measurement. One measurement can't reveal them all: measuring in the Z basis only gives the Z-type expectations. I need an informationally complete set: measuring every qubit in X, Y and Z gives 3^N settings, 27 for three qubits. Each setting is repeated for shots; at 2000 shots per setting that's 54,000 measurements, and the standard error on each ⟨P⟩ is at most 1/√2000 ≈ 0.022.

Reconstruction. Linear inversion just plugs the estimated ⟨P⟩ into the formula above. It's unbiased, but with finite shots it routinely returns a matrix with negative eigenvalues: nonphysical. So I check the eigenvalues, and if any is below zero I don't report that matrix. Instead I run maximum-likelihood: parameterize ρ = T†T / tr(T†T), which is PSD by construction, and maximize the multinomial likelihood of the observed counts. That's convex, solved with a standard optimizer. MLE is slightly biased toward the interior of the state space but always physical.

Alternatives. Linear inversion is fine when shots are large and the state is nearly pure: it's fast and analytic. MLE is the default once noise is meaningful. Bayesian methods give a full posterior and honest credible intervals at more compute; reach for them when the uncertainty itself is the deliverable.

Validation. Three checks: eigenvalues in [0,1] with trace 1; a goodness-of-fit test, likelihood-ratio or chi-square against the observed counts, which flags a wrong model or drift; and uncertainty from bootstrapping the shot counts or from the Fisher information, reported as error bars per parameter, never a bare point estimate.

Failure modes. Readout bias: if P(1|0)=2% and P(0|1)=5%, every ⟨P⟩ is skewed. Detect it by preparing |0⟩ and |1⟩, measuring the confusion matrix, and inverting it. Drift: settings taken sequentially over minutes let the hardware move, so interleave settings and re-measure a reference. State-preparation inconsistency: if the source isn't the same state each shot, the reconstructed ρ is a mixture. Detect it by splitting shots into blocks and comparing reconstructions. And cost: 3^N settings and 4^N parameters means N=10 is already 59,049 settings, so past a handful of qubits you switch to compressed sensing or shadow tomography.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-23

Represent and validate a quantum state for statevector simulation.

Answer

A statevector is the full state of an n-qubit register written in the computational basis: a vector of 2^n complex amplitudes, one per basis state, normalized so Σ|α_i|² = 1. Represent it as a complex128 array: 16 bytes per amplitude, so 2^n·16 bytes total: 30 qubits is 16 GiB, 50 qubits is 18 PB. Global phase is unobservable, so any comparison must be up to phase.

Validation has three layers, and they answer different questions. Structural: is it length 2^n and normalized? Numerical: does it match a reference within tolerance? Operational: does it match hardware or finite-shot counts? Only the first two validate the circuit mathematics; the third validates the device.

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

qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
sv = Statevector.from_instruction(qc)

sv.is_valid()                 # True — normalized, length 4
np.round(sv.data, 4)          # [0.7071+0.j, 0.+0.j, 0.+0.j, 0.7071+0.j]
sv.probabilities()            # [0.5, 0.0, 0.0, 0.5]

ref = Statevector([1/np.sqrt(2), 0, 0, 1/np.sqrt(2)])
sv.equiv(ref)                 # True — up to global phase

Statevector.__eq__ was removed in Qiskit 1.0; equiv() is the tolerance comparison and ignores global phase (rtol 1e-5, atol 1e-8 by default). Exact == on the raw array fails on a correct state whenever a global phase or float rounding differs.

Trace the ordering, because it is the most common false failure. Qiskit is little-endian: qubit 0 is the least significant bit of the basis index. After H on q0 the state is [1/√2, 1/√2, 0, 0]: index 1 is |q1q0⟩ = |01⟩. CX(0,1) moves that amplitude to index 3, giving |00⟩ and |11⟩ at 0.5 each. A reference that puts the excitation at index 2 is big-endian; the circuit is fine and the comparison is wrong.

Alternatives, and when each wins:

methodmemoryhandles noiselimit
statevector2^n·16 Bnoexact amplitudes, exponential
density matrix4^n·16 Byes10 qubits ≈ 16 MiB
stabilizerpoly(n)noClifford gates only
MPS / tensor networkO(n·χ²)nolow entanglement only

Statevector is the right default for small circuits because it gives every amplitude exactly. Reach for density matrix when you need noise, stabilizer when the circuit is Clifford and n is large, MPS when entanglement stays low.

Failure modes and how to catch them:

  • Non-normalized hand-built vector: is_valid() returns False; a norm of 1.0001 is a bug, not rounding.
  • Ordering mismatch: compare a deliberately asymmetric state (X on q0 alone gives index 1, not 2).
  • Ideal amplitudes vs finite shots: with 1024 shots at p=0.5, the binomial σ is √(0.25/1024) ≈ 0.016, so a 3σ band is ±0.047. A deviation inside that band is not a simulator bug.
  • Mid-circuit measurement, reset, or dynamic circuits: Statevector.from_instruction raises; use save_statevector with AerSimulator(method="statevector") instead.
  • Memory blowup: 2^n·16 bytes crosses a 64 GiB node at 32 qubits; check n before launching.

Curated: · Written: · Reviewed:

Difficulty: Medium