Level 6 · Practitioner’s Corner

Deutsch–Jozsa and Bernstein–Vazirani in Qiskit

About 5,031 words · roughly 23 minute read · sources checked December 2, 2026

Two of the earliest quantum algorithms answer a question with a single call to a black-box function, where a classical computer would need many. Deutsch–Jozsa tells you whether a function is constant or balanced. Bernstein–Vazirani finds a hidden bitstring. Both are tiny enough to build in a few lines of Qiskit, and both teach one idea that returns in nearly every later algorithm: phase kickback.

They are also easy to over-sell. The speed-ups are real but come with strong conditions, and neither solves a problem anyone needs solved. This lesson shows the circuits, gives every result computed exactly, and says plainly what the comparison with classical computing does and does not mean.

As in the other Qiskit lessons here, I could not run Qiskit in my environment. The code is written from the documented behaviour of the library, and every output is from my own NumPy simulation of the same gates, with Qiskit’s bit ordering (qubit 0 is the rightmost character of a result string). Run it yourself and compare.

What you will learn

  • What phase kickback is and why a qubit in the state |−⟩ turns a function call into a sign flip.
  • How to build oracles for XOR-type functions from CNOT gates.
  • How Bernstein–Vazirani reads out a hidden bitstring in one query.
  • How Deutsch–Jozsa separates constant from balanced functions, and what happens if the promise is broken.
  • How many queries a classical computer needs for the same tasks.
  • How to read the results from a Sampler in Qiskit’s bit order.

Helpful first: Your First Qiskit Circuit, Quantum Algorithms.

The one trick: phase kickback

Both algorithms rely on the same move. A function f takes an n-bit input x and returns one bit. A quantum oracle for f acts on the n input qubits plus one extra ancilla qubit y, and it computes y XOR f(x) in the ancilla. If the ancilla starts in the state |−⟩ = (|0⟩ − |1⟩)/√2, something neat happens: instead of changing the ancilla, the oracle multiplies the input by a sign.

oracle:  |x⟩|y⟩  →  |x⟩|y ⊕ f(x)⟩
ancilla in |−⟩ = (|0⟩ − |1⟩)/√2:
|x⟩|−⟩  →  (−1)^f(x) |x⟩|−⟩
Phase kickback. The answer f(x) ends up as a sign on the input, and the ancilla is unchanged.

Worked example

Why the sign appears

  1. Take f(x) = 0. The oracle leaves y alone, so |x⟩|−⟩ is unchanged. The sign is (−1)⁰ = +1.
  2. Take f(x) = 1. The oracle flips y: |0⟩ becomes |1⟩ and |1⟩ becomes |0⟩. So (|0⟩ − |1⟩)/√2 becomes (|1⟩ − |0⟩)/√2, which is −|−⟩.
  3. That minus sign belongs to the whole joint state, so it can be written in front of |x⟩. The ancilla is back in |−⟩ and plays no further part.

Now put the inputs into an equal superposition of all 2ⁿ values. The oracle gives each term its own sign (−1)^f(x), all in a single call. What remains is to turn that pattern of signs into something we can read out, and that is the job of a second layer of Hadamard gates.

In Qiskit terms

To get the ancilla into |−⟩ you apply X then H to a qubit that starts in |0⟩: X makes it |1⟩, and H makes |1⟩ into |−⟩. After the algorithm you can undo this, or simply not measure the ancilla.

Bernstein–Vazirani: find the hidden bitstring

A hidden n-bit string s is built into a function f(x) = s · x (the dot product, taken modulo 2). You may call f on any input and get one bit back. The task is to find s. Classically you need n calls: ask for each unit vector, and the answers are the bits of s. The quantum circuit needs one.

The circuit

from qiskit import QuantumCircuit
from qiskit.primitives import StatevectorSampler

def bernstein_vazirani(s):
    n = len(s)
    qc = QuantumCircuit(n + 1, n)       # n input qubits, 1 ancilla, n classical bits
    qc.x(n)                             # ancilla -> |1>
    qc.h(range(n + 1))                  # inputs -> |+>, ancilla -> |->
    # oracle for f(x) = s . x : a CNOT from each qubit where s has a 1
    for i, bit in enumerate(reversed(s)):
        if bit == '1':
            qc.cx(i, n)
    qc.h(range(n))                      # second layer of Hadamards
    qc.measure(range(n), range(n))      # read the n input qubits
    return qc

qc = bernstein_vazirani('101')
counts = StatevectorSampler().run([(qc, None, 1024)]).result()[0].data.c.get_counts()
print(counts)        # expected: {'101': 1024}
Bernstein–Vazirani for a hidden string. Not run in Qiskit here. The register is called c because we created the circuit with an integer number of classical bits; check the name in your version.

The oracle is just a few CNOT gates. A CNOT from qubit i to the ancilla flips the ancilla when qubit i is 1, so after the CNOTs the ancilla holds the XOR of the input bits where s has a 1. That is s · x modulo 2, exactly the function we want. The reversed(s) in the loop is there because Qiskit’s qubit 0 is the rightmost character of a string.

Why it reads out s

After the first Hadamards and the oracle, the input register holds an equal superposition with signs (−1)^(s·x) on each term. The second layer of Hadamards turns exactly that sign pattern into the single basis state |s⟩. So the measurement returns s with certainty. I checked this by simulation for many strings.

Hidden string sMeasured result (exact simulation)Probability
1011011.0
1101101.0
0110111.0
1111111.0
0000001.0
10110101101.0

My NumPy simulation of the circuit above. In every case the output equals the hidden string with probability 1 and no other string appears.

The case s = 000

If s is all zeros the function is always 0, so no CNOTs are applied and the oracle does nothing. The circuit still returns 000, correctly.

The classical comparison is exact: to find an n-bit s you need n calls. For n = 3 that is 3 calls against 1, for n = 10 it is 10 against 1, and for n = 20 it is 20 against 1. This is a modest advantage (linear in n), and it holds only when f has exactly the form s · x.

Deutsch–Jozsa: constant or balanced?

Now a different question. You are told a function f on n bits is either constant (the same output for all 2ⁿ inputs) or balanced (0 for exactly half of the inputs and 1 for the other half). You are promised it is one or the other. Which?

Classically, in the worst case you must check just over half of the inputs: 2ⁿ⁻¹ + 1 calls. If the first 2ⁿ⁻¹ answers are all equal, one more call tells you whether the function is constant. The quantum circuit uses one call.

from qiskit import QuantumCircuit
from qiskit.primitives import StatevectorSampler

def deutsch_jozsa(oracle, n=3):
    qc = QuantumCircuit(n + 1, n)
    qc.x(n)
    qc.h(range(n + 1))
    oracle(qc, n)                       # a function that adds the oracle gates
    qc.h(range(n))
    qc.measure(range(n), range(n))
    return qc

def constant_zero(qc, n):  pass                 # f(x) = 0
def constant_one(qc, n):   qc.x(n)              # f(x) = 1
def balanced_x0(qc, n):    qc.cx(0, n)          # f(x) = x0
def balanced_x0_x2(qc, n): qc.cx(0, n); qc.cx(2, n)   # f(x) = x0 XOR x2

for oracle in (constant_zero, constant_one, balanced_x0, balanced_x0_x2):
    qc = deutsch_jozsa(oracle)
    counts = StatevectorSampler().run([(qc, None, 1024)]).result()[0].data.c.get_counts()
    print(oracle.__name__, counts)
Deutsch–Jozsa on three input qubits with four example oracles. Not run in Qiskit here.

The rule for reading the result is simple: if every measured bit is 0, the function is constant. If any bit is 1, it is balanced. The reason is that the amplitude on 000 is the average of (−1)^f(x) over all inputs. For a constant function that average is ±1, so the probability of 000 is 1. For a balanced function the plus and minus signs cancel exactly, so the probability of 000 is 0.

FunctionKindCircuit gates in the oracleP(000)Most likely result
f(x) = 0constantnone1.0000
f(x) = 1constantX on the ancilla1.0000
f(x) = x0balancedCNOT from qubit 00.0001
f(x) = x0 XOR x2balancedCNOTs from qubits 0 and 20.0101
f(x) = 1 when x < 4balancedCNOT from qubit 2, then X on the ancilla0.0100

My NumPy simulation, exact. The balanced results are not 000, so the algorithm says ‘balanced’ with certainty. Results are written with qubit 0 on the right.

Note the balanced example f(x) = 1 when x < 4

The inputs below 4 are those with qubit 2 equal to 0, so f is the NOT of x2. That is why the oracle is a CNOT from qubit 2 plus an X on the ancilla, and why the result is 100.

What if the promise is broken?

The algorithm’s guarantee covers only functions that really are constant or balanced. For anything else it gives a probabilistic hint, not a verdict. Two examples from my simulation:

Function (not constant, not balanced)How many inputs give 1P(000)Can you conclude anything?
f(x) = 1 only at x = 01 of 80.5625No: the result is 000 about 56% of the time, so it could mislead
f(x) = 1 at x = 0, 1, 23 of 80.0625No: you would probably see a non-zero string and call it ‘balanced’, wrongly

From my simulation. The first value is 0.75² = 0.5625 (worked below). The second is ((5 − 3)/8)² = 0.0625.

Worked example

Checking the 0.5625 by hand

  1. f = 1 only at x = 0. Of the eight inputs, one has sign −1 and seven have sign +1.
  2. The amplitude on 000 is the average of the signs: (7 − 1)/8 = 6/8 = 0.75.
  3. The probability is 0.75² = 0.5625, matching the simulation. So a ‘000’ result is common but is not proof of a constant function when the promise fails.

Every function on three bits

There are 2⁸ = 256 functions from three bits to one bit. Two are constant, and C(8,4) = 70 are balanced. The other 184 are neither. I ran the Deutsch–Jozsa circuit on all 256 in my simulation, and the result depends only on how many inputs give 1. If k inputs give 1, the amplitude on 000 is (8 − 2k)/8, so P(000) = ((8 − 2k)/8)².

Inputs giving 1 (k)Number of such functionsP(000)What the promise says
011.0000constant
180.5625neither: the promise is broken
2280.2500neither
3560.0625neither
4700.0000balanced
5560.0625neither
6280.2500neither
780.5625neither
811.0000constant

From my simulation of all 256 functions. The counts are the binomial numbers C(8,k), which add up to 256.

This table shows exactly why the promise matters. Outside the two promised cases, P(000) takes values strictly between 0 and 1 and tells you nothing definite. It also shows that the algorithm is symmetric: a function and its complement (swap 0 and 1 everywhere) give the same probability.

How many of the balanced functions are of the Bernstein–Vazirani form?

The functions f(x) = s · x, one for each of the 8 possible s, are the ones Bernstein–Vazirani handles. Seven of them (s not zero) are balanced, and s = 000 is the constant zero. So of the 70 balanced functions, only 7 are of this form, and the other 63 are balanced functions with no hidden string. Deutsch–Jozsa works on all 70, but Bernstein–Vazirani’s promise is narrower. I counted these in my simulation script by listing the dot-product functions.

How big is the speed-up, honestly?

The comparison is clean mathematically, but it needs care.

n (input bits)Classical calls, worst case (2ⁿ⁻¹ + 1)Quantum callsClassical calls for Bernstein–VaziraniQuantum calls
35131
105131101
20524,2891201

Computed from the formulas. Deutsch–Jozsa’s classical worst case is exponential in n; Bernstein–Vazirani’s is linear.

  • Deutsch–Jozsa’s advantage over a deterministic classical algorithm is exponential, but a classical computer that is allowed a tiny chance of error does far better. By picking a few random inputs it can decide with very high confidence, so the practical advantage is much smaller than the table suggests. I am stating this from the general theory and did not check it against a source in this session.
  • Both problems are artificial. They were designed to show a separation between quantum and classical query counts, not to solve a useful task.
  • The comparison counts calls to the oracle, and ignores the cost of building it. In the real world a function has to be implemented as a circuit, and that circuit takes time.
  • On a noisy device, the guarantee of a perfect result goes away. The more qubits and gates, the more errors.

So why teach them? Because they are the smallest clear examples of three ideas used by every later algorithm: phase kickback, interference through Hadamard layers, and the idea that a quantum computer can extract a global property of a function from a single call. Shor’s algorithm and the Quantum Fourier Transform lesson that follows this one use the same ingredients.

Run the circuits in your browser first

Before you write any Qiskit, it helps to see these circuits behave. The widgets below run on this site's own simulator, with no installation, and they use the same gates as the Qiskit code in this lesson. Each one asks you to predict the result before you press Run. Remember that the displayed bitstrings follow the Qiskit convention, with qubit 0 as the rightmost bit.

Bernstein–Vazirani with the secret 101

Run this circuit

Bernstein–Vazirani, secret s = 101

q0q1q2q3XHHHHHHH

Bit order: q0 is the rightmost digit of each result, as in Qiskit. All qubits start in |0⟩ unless marked. This is an ideal simulator with no hardware noise.

Predict first: The oracle computes f(x) = s·x with CNOTs from qubits 0 and 2 into the ancilla. What does the 3-bit readout look like?

Press Run to simulate. Results appear here with a short explanation.

Deutsch–Jozsa: a constant function

Run this circuit

Deutsch–Jozsa, constant f(x) = 0

q0q1q2XHHHHH

Bit order: q0 is the rightmost digit of each result, as in Qiskit. All qubits start in |0⟩ unless marked. This is an ideal simulator with no hardware noise.

Predict first: The oracle does nothing (f = 0 for every input). What do the input qubits read?

Press Run to simulate. Results appear here with a short explanation.

Deutsch–Jozsa: a balanced function

Run this circuit

Deutsch–Jozsa, balanced f(x) = x₀ ⊕ x₁

q0q1q2XHHHHH

Bit order: q0 is the rightmost digit of each result, as in Qiskit. All qubits start in |0⟩ unless marked. This is an ideal simulator with no hardware noise.

Predict first: Qubit 2 is the ancilla in |−⟩. Only the two input qubits are read out. If f is constant you would read 00. This f is balanced.

Press Run to simulate. Results appear here with a short explanation.

Compare the last two. The only difference between the circuits is the oracle: nothing in the constant case and two CNOT gates in the balanced one. The readout differs in every single shot, 00 against 11, which is what makes one run enough to decide.

Why measure only the inputs

The ancilla qubit holds the oracle's output and is left in the minus state. It carries no useful information at the end, so we leave it unmeasured. In the widget this is set by choosing which qubits to read out.

Two calculations by hand

A good test of understanding is to follow the amplitudes yourself. We do one small case of each algorithm with two input qubits. The ancilla is in the minus state throughout, so the oracle acts as a sign flip on the inputs and we can ignore the ancilla and track only the two input qubits.

Bernstein–Vazirani with s = 11

Worked example

Tracking the amplitudes

  1. Start with the inputs in |00⟩ and apply H to both: the state is (1/2)(|00⟩ + |01⟩ + |10⟩ + |11⟩).
  2. The function is f(x) = x₀ ⊕ x₁, because s = 11 selects both bits. The oracle multiplies each term by (−1)^f(x).
  3. f(00) = 0, f(01) = 1, f(10) = 1, f(11) = 0, so the signs are +, −, −, +.
  4. The state is now (1/2)(|00⟩ − |01⟩ − |10⟩ + |11⟩).
  5. Apply H to both qubits again. The amplitude of |11⟩ after the last layer is (1/4)·Σₓ (−1)^(x·11)·(−1)^f(x) where x·11 = x₀ ⊕ x₁ is the same bit as f(x).
  6. So every term is (−1)^(f)·(−1)^(f) = +1, and the sum of the four terms is 4. The amplitude is (1/4)·4 = 1.
  7. All the probability sits on |11⟩, so the measurement returns 11 with certainty. The hidden string is 11.

The reason is visible in the exponent: the second layer of Hadamards multiplies each term by (−1)^(x·y) for the output y, and when y equals the secret s the two signs cancel everywhere, so all terms add. For any other y the signs disagree on half the terms and they sum to zero.

Deutsch–Jozsa with a constant function

Worked example

Tracking the amplitudes

  1. After the first layer of H gates the inputs are (1/2)(|00⟩ + |01⟩ + |10⟩ + |11⟩).
  2. For a constant function f = 0, the oracle multiplies every term by +1, so nothing changes. For f = 1 it multiplies every term by −1, which is a global phase.
  3. The second layer of H maps (1/2)Σₓ|x⟩ back to |00⟩ exactly.
  4. The amplitude of |00⟩ is therefore 1 (or −1 for f = 1), and the probability of reading 00 is 1.

Deutsch–Jozsa with a balanced function

Worked example

Tracking the amplitudes

  1. Take f(x) = x₀ ⊕ x₁, which is balanced: f is 1 on exactly two of the four inputs.
  2. The state after the oracle is (1/2)(|00⟩ − |01⟩ − |10⟩ + |11⟩), the same state as in the Bernstein–Vazirani calculation above.
  3. The amplitude of |00⟩ after the final H layer is (1/4)(1 − 1 − 1 + 1) = 0.
  4. So reading 00 is impossible, which is the signature of a balanced function.

Notice that the balanced example is the same circuit as Bernstein–Vazirani with s = 11. That is not a coincidence. The function x₀ ⊕ x₁ is both balanced and linear, so both algorithms apply, and each reads out the answer that it is built to find: DJ says not constant, BV reports the string 11.

Counting queries: quantum, deterministic and randomised

The speed-up claims in textbooks are about the number of oracle queries. Let us tabulate them carefully, because the comparison depends on which classical algorithm you have in mind.

Input bits nBV classical queriesBV quantum queriesDJ deterministic classical, worst caseDJ quantum queries
22131
33151
551171
101015131
20201524,2891

Query counts from the formulas n for BV and 2^(n−1) + 1 for deterministic DJ. My own arithmetic.

For Bernstein–Vazirani the classical cost is n, so the quantum saving is a factor of n, which is real but modest. For Deutsch–Jozsa the deterministic classical cost explodes, but that comparison is unfair to classical computing, because a randomised algorithm can do far better.

A randomised classical algorithm for DJ

Suppose the function is promised to be constant or balanced. Query k random inputs. If any two answers differ, the function is certainly balanced. If all k answers agree, guess constant. A constant function always passes, and a balanced function fools the test only if all k answers happen to agree. Sampling with replacement, the probability of that is 2·(1/2)^k, because the answers must all be 0 or all be 1.

Queries kProbability of a wrong answer on a balanced function
11 (a single query tells you nothing)
20.5
30.25
50.0625
100.00195
200.0000019

Error probability of the randomised test, 2·(1/2)^k. My own calculation.

Ten queries already push the error below two parts in a thousand, independent of n. So the practical separation between DJ and a randomised classical algorithm is at most a few queries, and no exponential. The quantum algorithm gives certainty with one query, which is elegant, but the proven exponential gap is between quantum and deterministic classical only.

What to take away

Deutsch–Jozsa is a teaching result about what a single query can do, and an honest statement of its speed-up always names the comparison class: deterministic classical, randomised classical or both.

What noise does to these circuits

The textbook results are for perfect gates. Real devices make errors, and these circuits are a good first test because the correct answer is known. I wrote a small NumPy density-matrix simulation for this lesson. After every gate it applies depolarising noise with probability p: a random non-identity Pauli error on the qubits the gate touched. For two-qubit gates the error is chosen from the fifteen non-identity two-qubit Paulis. This is a simple model and not a model of any particular device. It is my own code, run in NumPy, and not Qiskit.

Gate error pBV, s = 101 (4 qubits, 10 gates): P(correct)DJ balanced, 2 inputs (3 qubits, 10 gates): P(read 11)
01.00001.0000
0.0010.99340.9947
0.010.93570.9482
0.020.87570.8994
0.050.72000.7696
0.100.52630.6011

My own density-matrix simulation with depolarising noise after every gate. Not Qiskit, and not a model of a specific device.

Read the table as a rule of thumb. With ten gates and a one percent error per gate, the chance of a correct answer is about 94 percent, close to the crude estimate (1 − p)^10 = 0.904 that treats every error as fatal. The actual number is a bit higher because some errors do not change the outcome, for instance a Z error on a qubit just before it is measured in the standard basis. As p grows, the success probability falls towards the 1/8 chance of a random three-bit guess for the BV case, though at p = 0.1 it is still 0.53.

(1 − 0.01)^10 = 0.9044
(1 − 0.001)^10 = 0.9900
(1 − 0.05)^10 = 0.5987
Crude independent-error estimates for ten gates. They are lower bounds on success in this model, which the simulated values exceed.

The practical lessons are two. First, use these circuits as a smoke test on a real device: if BV on three or four qubits does not return the secret most of the time, something is wrong with the transpilation or the device. Second, increase n and you will see the success probability fall, because the circuit has more gates and more chances for error. The CNOT gates are usually the largest error source, so a secret with many ones is harder than one with a few.

Gate counts and what grows with n

For Bernstein–Vazirani with n input bits, the circuit uses one X gate, 2n + 1 Hadamard gates in total counting the ancilla's, and one CNOT for each 1 in the secret, so between 0 and n CNOTs. Measurement adds n readouts.

nHadamardsX gatesCNOTs (worst case s = all ones)Total gates, worst case
371311
5111517
102111032
204112062

BV gate counts: 2n + 1 Hadamards, one X, and up to n CNOTs. My own count.

The count is linear in n, so the circuit is cheap. The catch is that real hardware connects each qubit to a few neighbours, and a CNOT from every input to one shared ancilla needs many extra swap gates on a chip with limited connectivity. A transpiler inserts them. On a line of qubits with the ancilla at one end, the farthest input needs about n − 1 swaps to reach the ancilla, so the real gate count grows quadratically in n. This is a good example of why the abstract circuit count is not the cost on hardware, and why our lesson on circuit diagrams and transpilation matters.

Depth

The circuit depth, meaning the number of sequential layers, is small in the ideal case: one layer for X, one for the Hadamards, then the oracle CNOTs, which all share the ancilla and so must be sequential, adding up to n layers, then one more Hadamard layer. So the depth grows linearly with the number of ones in the secret. The ancilla is the bottleneck. A variant that avoids the shared ancilla by preparing it differently does not remove the serial nature of the CNOTs onto a single target.

Debugging these circuits

Because the right answer is known in advance, these circuits are excellent debugging exercises. These are the problems I would check, in order.

  1. The answer is reversed. Qiskit prints qubit 0 as the rightmost bit. If you create the oracle with a loop over the string left to right, the secret appears reversed. The code above loops over reversed(s) to prevent this.
  2. The answer is all zeros when it should not be. The oracle CNOTs may not be applied, perhaps because the condition on the bit string character is wrong, or because the barrier or transpiler dropped them.
  3. The ancilla is not in the minus state. If the X before the Hadamard on the ancilla is missing, the ancilla is in the plus state, the oracle writes the function value into the ancilla's bit and not into a phase, and the input register ends in a mixture of results.
  4. The result is random. Check that the second layer of Hadamards is applied to the input qubits and that the measurement is on the inputs, not the ancilla.
  5. Counts do not sum to the shots. Some tools return probabilities, others counts, and some return keys for classical registers with spaces when there are several registers.

Use the browser widgets on this page to cross-check. If the widget gives the secret and your Qiskit code does not, the bug is in the translation, usually bit order.

The same algorithm in Cirq

Bernstein–Vazirani is small enough to write in another framework, which is a good way to check that you understand the algorithm and not just one library's syntax. Here is a version in Cirq, Google's framework. It is not run here, because Cirq is not installed in the environment I used to prepare this lesson, so treat it as a sketch to check against the Cirq documentation.

import cirq

def bernstein_vazirani(s):
    n = len(s)
    q = cirq.LineQubit.range(n + 1)          # q[n] is the ancilla
    c = cirq.Circuit()
    c.append(cirq.X(q[n]))
    c.append(cirq.H.on_each(*q))
    for i, bit in enumerate(s):               # here s[0] is qubit 0
        if bit == '1':
            c.append(cirq.CNOT(q[i], q[n]))
    c.append(cirq.H.on_each(*q[:n]))
    c.append(cirq.measure(*q[:n], key='out'))
    return c

result = cirq.Simulator().run(bernstein_vazirani('101'), repetitions=1024)
print(result.histogram(key='out'))
Bernstein–Vazirani in Cirq. Not run. Check method names against your installed Cirq version.

Two differences are worth noticing. First, Cirq numbers the qubits in the order you list them and, when it packs the measurement results into an integer, treats the first listed qubit as the most significant bit, which is the opposite of Qiskit's printed bitstrings. The loop above therefore indexes the secret from the left, whereas the Qiskit code used reversed(s). The secret 101 is a palindrome, so it hides this difference, and a good test is to use 110 and check which way round the result appears. Second, Cirq separates building the circuit from running it in a simulator object, much as Qiskit does with its sampler primitives.

The algorithm itself did not change: one X, a layer of Hadamards, CNOTs from the qubits where the secret has a one, a second layer of Hadamards and a read-out. That portability is the point. Once you know the circuit, the framework is a matter of syntax, and the interactive widgets on this page are a framework-free reference to compare against.

Summary: what these two algorithms teach

Deutsch–Jozsa and Bernstein–Vazirani are small problems with a large lesson. Both use the same four-step recipe: prepare a uniform superposition, write a function into signs with phase kickback, undo the superposition with a second layer of Hadamards, and read the answer. Interference does the work, because amplitudes with the wrong sign cancel and amplitudes with the right sign add.

  • Bernstein–Vazirani finds an n-bit secret with one query instead of n, a modest but real saving, with certainty.
  • Deutsch–Jozsa decides constant versus balanced with one query, and the exponential gap holds only against deterministic classical algorithms.
  • Both circuits are shallow, so they make good smoke tests for a framework or a device, and noise lowers their success rate in a predictable way.
  • The same pattern, with a harder hidden structure, powers Simon's algorithm and Shor's algorithm, which is why it is worth learning properly before moving on.

Common mistakes

  • Forgetting to prepare the ancilla in |−⟩. Without the X then H on the ancilla, the oracle does not produce a sign, and the output is not what the theory says.
  • Reading the output in the wrong order. Qubit 0 is the rightmost character. For the oracle f(x) = x0 the answer is 001, not 100.
  • Measuring the ancilla and including it in the result string. Measure only the input qubits, as the circuit above does.
  • Using the wrong register name. A circuit built with QuantumCircuit(n + 1, n) has a classical register named c, whereas measure_all() creates one named meas. Check the name if you get an attribute error.
  • Applying Deutsch–Jozsa to a function that is neither constant nor balanced and trusting the answer.
  • Expecting exact results on real hardware. Noise can produce wrong strings even when the function is simple.

Questions people ask

Do these algorithms solve any real problem?

No. They are teaching examples that show a gap in query counts. Their value is in the ideas they introduce.

Why does Bernstein–Vazirani use the same circuit as Deutsch–Jozsa?

Both are an equal superposition, an oracle that writes signs, and a second layer of Hadamards that converts the sign pattern into a readable result. Only the function and how you read the output differ.

Why is the second Hadamard layer needed?

Without it the signs are invisible, because measuring right after the oracle gives every outcome with equal probability. The second layer makes the signs interfere.

Is one oracle call really one step?

It is one call to the black box, which may itself be a long circuit. The speed-up is in the number of calls.

Can I run these on real IBM hardware?

Yes in principle, but the circuits must be transpiled to the device’s gate set, and noise will spoil the exactness. The lesson on moving from simulator to hardware covers the steps.

Practice problems

Check yourself

What does the ancilla do in phase kickback, and what state must it start in?

It lets the oracle’s XOR act as a sign (−1)^f(x) on the input. It must be in |−⟩, made with X then H.

In Bernstein–Vazirani with s = 110, which qubits need a CNOT to the ancilla?

Qubits 1 and 2. The string 110 has qubit 2 = 1, qubit 1 = 1, qubit 0 = 0.

How many oracle calls does a classical computer need to find a 20-bit hidden string by this method?

20, one per bit.

For Deutsch–Jozsa with n = 4, what is the classical worst-case number of calls?

2³ + 1 = 9.

A function is 1 on exactly 2 of 8 inputs. What does the 000 amplitude equal, and what is P(000)?

The signed average is (6 − 2)/8 = 0.5, so P(000) = 0.25.

Why does measuring right after the oracle tell you nothing?

The oracle changes only signs, which do not change probabilities. The second Hadamard layer turns the signs into probabilities.

For f(x) = x1 on three input qubits, what result do you expect?

010. The oracle is a CNOT from qubit 1, so the string has a 1 in position 1 (counting from the right, starting at 0).

References and further reading

I opened IBM’s Sampler guide for the pattern of building a circuit, running a Sampler and reading results from a named classical register. The first Qiskit lesson on this site relied on the Qiskit documentation on bit ordering and on primitive outputs. I could not run Qiskit here, so none of the code was executed; every printed result is from my own NumPy simulation of the same gates using Qiskit’s bit ordering. The two algorithms are standard textbook results, which I verified by that simulation rather than by quoting a source. Package versions change, so check your own.

  1. Get started with Sampler (IBM Quantum documentation) Opened. Pattern of building a circuit, running a Sampler and reading results from a named classical register. Uses SamplerV2 from qiskit_ibm_runtime and get_bitstrings(); this site’s first Qiskit lesson used StatevectorSampler and get_counts() from other documentation pages.
  2. IBM Quantum documentation (IBM) Opened. Overview of Qiskit guides, tutorials and API references.

Key terms in the dictionary