Bernstein–Vazirani in Qiskit: Find a Secret String in One Query

Here is a puzzle. A black box hides a secret bit string s of length n. You can feed it any string x, and it answers with one bit: the parity of the bits where x and s are both 1 (the dot product s·x mod 2). How many questions do you need to recover s?

Classically the answer is n: ask with 1000…0 to learn the first bit, 0100…0 for the second, and so on — each answer gives you exactly one bit. The Bernstein–Vazirani algorithm does it with one query. This post builds it in Qiskit, explains why it works, and checks how it holds up on a noisy model of IBM's ibm_fez.

Why one query is enough

The trick is phase kickback. Put an extra "answer" qubit in the state |−⟩ (X then H). When the oracle flips that qubit conditionally on s·x, the flip turns into a sign: the input register picks up a phase of (−1)s·x. If the input register is in an equal superposition of all strings — Hadamards on every qubit — every possible x gets its own sign at once.

A second layer of Hadamards then acts as a Fourier transform over bit strings. The pattern of signs (−1)s·x is exactly the signature of the single string s, so all amplitude concentrates there. Measure, and you read s directly.

It is worth being precise about what this shows. The speed-up is real but modest (n queries down to 1, not exponential), and the oracle is a contrived problem. Its value is pedagogical: it is the cleanest demonstration of phase kickback and interference, the two ideas behind almost every quantum algorithm.

Building the oracle

The oracle for s is just a CNOT from each input qubit where s has a 1 to the answer qubit. One detail trips people up: Qiskit prints bitstrings little-endian, so qubit 0 is the rightmost character. The loop below reverses the string so that the printed result matches s as written.

from qiskit import QuantumCircuit

def bernstein_vazirani(secret):
    n = len(secret)
    qc = QuantumCircuit(n + 1, n)
    qc.x(n); qc.h(range(n + 1))                 # inputs in |+>, answer qubit in |->
    for i, bit in enumerate(reversed(secret)):  # qubit i <-> rightmost character
        if bit == "1":
            qc.cx(i, n)                         # the oracle: one CNOT per 1 in s
    qc.h(range(n))                              # interfere
    qc.measure(range(n), range(n))
    return qc

Running it

from qiskit_aer import AerSimulator
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit_ibm_runtime import SamplerV2 as Sampler
from qiskit_ibm_runtime.fake_provider import FakeFez

backend = FakeFez()
pm = generate_preset_pass_manager(backend=backend, optimization_level=1)
sampler = Sampler(mode=backend)

for s in ["101101", "1011010111"]:
    ideal = AerSimulator().run(bernstein_vazirani(s), shots=2000).result().get_counts()
    isa = pm.run(bernstein_vazirani(s))
    noisy = sampler.run([isa], shots=20000).result()[0].data.c.get_counts()
    print(s, ideal, noisy.get(s, 0) / 20000, isa.depth())

Results

SecretIdeal simulatorNoisy ibm_fez model: P(correct)Transpiled depth
101101 (6 bits)100%94.9%22
1011010111 (10 bits)100%87.3%53–61

On the ideal simulator every single shot returns the secret. On the noisy model the correct string is still by far the most common outcome — so a majority vote over a few hundred shots recovers s reliably — but the success rate drops as the string grows.

The reason is in the last column. The oracle needs a CNOT from many input qubits to one answer qubit, and on a heavy-hex chip those qubits are not all neighbours. The transpiler adds SWAP gates to bring them together, and the depth more than doubles from 6 to 10 bits. (The exact depth changes a little between runs, because the transpiler's layout search has a random component; pass seed_transpiler to make it repeatable.) Every extra two-qubit gate is another chance for an error. This is the everyday reality of NISQ hardware: the algorithm is perfect on paper, and the hardware's connectivity decides how much of that survives.

Things to try

  • Print isa.count_ops() to see how many SWAPs the transpiler inserted, then try optimization_level=3.
  • Pick a secret with fewer 1s: fewer CNOTs means less routing and a higher success rate.
  • Compare with the classical approach: n separate runs of a circuit with a single CNOT each. Which one wins on noisy hardware for n = 10?

References

  • E. Bernstein and U. Vazirani, "Quantum complexity theory," SIAM Journal on Computing 26(5), 1411–1473 (1997).
  • M. A. Nielsen and I. L. Chuang, Quantum Computation and Quantum Information, Cambridge University Press — chapter on quantum algorithms.
  • Qiskit documentation: transpilation and preset pass managers.

Comments

Popular posts from this blog

Quantum Key Distribution for Developers — BB84 with Qiskit

Qiskit Runtime & the Primitives — SamplerV2 and EstimatorV2 in 2026

Post-Quantum Cryptography in 2026 — What Developers Actually Need to Know