Algorithmresearch
Barman-Krishnamurthy-Vaish algorithm
Also called EF1 and Pareto optimal allocation algorithm.
Finds an EF1 and Pareto optimal allocation of indivisible goods in pseudo-polynomial time by running a market with price rises.
- Time
- poly(n, m, V) worst
- Space
- O(n m) extra
- Where
- V = the largest value v_max (an integer); m = the number of goods; n = the number of agents
- Model
- Word RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
The Barman-Krishnamurthy-Vaish (BKV) algorithm finds an allocation of indivisible goods that is both envy-free up to one good (EF1) and Pareto optimal (PO), for additive valuations, in time polynomial in , and the largest value . It treats the goods as a Fisher market: goods have prices, every agent holds only goods of maximum value per unit of price, so the allocation is efficient by the first welfare theorem, and the algorithm moves goods and raises prices until the spending of the agents is balanced up to one good. Maximum Nash welfare also gives EF1 and PO (the unreasonable fairness of MNW), but it is NP-hard to compute; BKV reaches the same two properties in pseudo-polynomial time. Barman, Krishnamurthy and Vaish presented it at EC 2018. Whether EF1 and PO can be reached in polynomial time is open (open problem, Mahara, November 2024).
In plain words
Put a price tag on every item. Each person looks at the value they get for each unit of money and only keeps items that are the best deal for them. When everybody holds only best deals, no trade can help someone without hurting someone else.
Now look at the money each person has spent on their items. If someone spent far more than the poorest person, even after ignoring their most expensive item, things are unfair. Then either an item moves from a rich person to a poorer person who also sees it as a best deal, or, when no such move is possible, the prices of the items held by the poorer group go up. Higher prices make other items better deals for that group, which opens new moves. When spending is balanced up to one item, the values are balanced up to one item too.
The problem
There are agents and indivisible goods, with additive values . The goal is an allocation of all goods that is EF1 and PO.
Market terms. Prices are attached to the goods, and is the spending on a set . The bang per buck of agent for good is , its largest value is the MBB ratio , and the goods that reach it form the MBB set of . An allocation satisfies the MBB condition if every agent owns only goods of its MBB set. A least spender is an agent of smallest spending . The allocation is price-EF1 (pEF1) if for all agents with some has ; equivalently, for every agent .
Hierarchy. Start from the least spenders at level 0. An agent at level adds to level every agent not seen yet that owns an MBB good of . This is a breadth-first search along MBB edges (from an agent to a good) and allocation edges (from a good to its owner). A path violator is an agent at level with a good that is an MBB good of some agent at level , such that .
The algorithm
The page gives the exact form of the algorithm, with no rounding, and with all least spenders at level 0; the paper's form is described after the walk-through.
BKV-EXACT(v) ▷ n agents, m goods, values v_ij > 0- 1
give each good j to an agent k of largest v_kj, and set p_j ← v_kj - 2
loop - 3
if x is pEF1 for p then exit the loop - 4
H ← the hierarchy of the least spenders (levels by BFS) - 5
look for a path violator h with its good j and a parent g one level above - 6
if one is found then give j to g, and go back to line L3 - 7
α1 ← min over h ∈ H and goods j owned outside H of β_h p_j / v_hj - 8
α2 ← max over agents k ∉ H of (p(x_k) - max_{j ∈ x_k} p_j) / p_min - 9
α3 ← min over agents k ∉ H of p(x_k) / p_min - 10
α ← min(α1, α2, α3); multiply the price of every good owned in H by α - 11
if α = α2 then exit the loop - 12
return x
Line L1 is Phase 1 of the paper: each good goes to an agent that values it most, at a price equal to that value, so every owner gets bang per buck 1 from its goods and nobody gets more from any good. Lines L4 to L6 are Phase 2: a swap moves a good one level down the hierarchy, toward the least spenders, along an MBB edge, so the MBB condition stays true. Lines L7 to L10 are Phase 3: the prices of all goods held inside rise by the same factor. The three bounds stop the rise at the first event: at a good outside becomes an MBB good of an agent in , so grows; at the least spenders have caught up with every agent outside , up to one good; at an agent outside becomes a least spender.
The paper's version. Barman, Krishnamurthy and Vaish run the same three phases with a parameter on a rounded instance, whose positive values are rounded up to integer powers of , and test -versions of the violator conditions. They show that the run takes time (Lemma 4) and returns a -EF1 and fractionally PO allocation of the rounded instance (Lemma 3). For , this allocation is EF1 and PO for the original integer values (Lemma 5 and Theorem 1). The paper also handles zero values and a single least spender chosen by a fixed order.
Example
Three agents value four goods :
| agent 1 | 5 | 8 | 1 | 6 |
| agent 2 | 3 | 1 | 2 | 2 |
| agent 3 | 1 | 5 | 4 | 4 |
- Line L1. Agent 1 gets and agent 3 gets , at prices . Spending is 19, 0 and 4. Agent 1 spends without its most expensive good, so the allocation is not pEF1.
- Swap. The least spender is agent 2. Its MBB ratio is , reached by , which agent 1 owns, so agent 1 is at level 1. Since , agent 1 is a path violator, and moves to agent 2. Spending is now 14, 5 and 4.
- Price rise. The least spender is agent 3, with ; its only MBB good is its own , so . Then , and . The price of rises by to 5.
- Price rise. Agents 2 and 3 both spend 5 and form level 0, each holding only its own MBB good. Now (agent 3 and good : ), and . The prices of and rise to 6, and since the loop ends.
The output is , , with prices and values 14, 3 and 4. It is pEF1: . Agent 3 values at 9 but without at , its own value, so it is EF1; and it is PO.
Correctness
Three facts hold whenever the algorithm returns. First, the MBB condition holds at every step: line L1 makes it true, a swap moves a good to an agent for which it is an MBB good, and the bound keeps the MBB goods of agents in ahead of goods outside , while agents outside own only goods whose prices do not change. Second, the output is pEF1: either line L3 saw it, or the rise stopped at and the least spenders, which are inside because , now spend at least as much as every agent's spending minus its most expensive good. Third, pEF1 with the MBB condition gives EF1, because agent values any set at most and its own bundle at exactly (Lemma 2 of the paper). The MBB condition also gives PO by the first welfare theorem: an allocation that some agent prefers and nobody likes less would cost more than the total price of all goods. The full proof of these facts is in proofs/correctness.md. That the exact form ends is not proved; the paper proves termination for its rounded form.
Proof: When the exact BKV algorithm returns, its allocation is EF1 and Pareto optimalpartial
Setting. There are agents and goods with values . We refer to the lines L1 to L12 of the page and use its terms: prices , spending , MBB ratio , MBB condition, least spender with spending , pEF1, hierarchy and path violator. This proof shows partial correctness: if the algorithm returns, the allocation is EF1 and Pareto optimal. It does not prove that the exact form ends. For the rounded form, Barman, Krishnamurthy and Vaish prove termination in time (Lemma 4 of their paper).
Lemma 1 (prices stay positive). At every step for every good .
Proof. Line L1 sets . A swap does not change prices. A rise multiplies some prices by , and Lemma 3 below shows .
Lemma 2 (MBB condition). At every step each agent owns only goods of its MBB set.
Proof. After line L1, the owner of good has , and every agent has for every good with owner , because values most. So and is an MBB good of .
A swap of line L6 gives to an agent for which is an MBB good, and changes no prices, so all MBB sets stay the same.
A rise of line L10 multiplies by the prices of the goods owned in . By the construction of the hierarchy, every MBB good of an agent of is owned by an agent of . For , the ratios of the goods owned in drop by the factor , so the ratio of its own goods becomes . A good owned outside keeps its price, and gives . So the goods of are still MBB goods of . For , the goods of keep their prices and the other prices do not drop, so the goods of are still MBB goods of .
Lemma 3 (a rise has ). When line L7 is reached, , and , wherever they are defined, and at least one is defined.
Proof. Line L7 is reached only if the allocation is not pEF1 and no path violator exists. All least spenders are at level 0 of , so every has , which gives . A good owned outside is not an MBB good of any , since otherwise its owner would be in ; so and .
Every agent has . At level 0 this holds because . At a level , agent owns a good that is an MBB good of an agent at level , and since is not a path violator, . Since the allocation is not pEF1, some agent has , and so . If , then and are defined, and . If , the least spenders own no goods, and are not defined, and is defined because the violator owns goods outside .
Lemma 4 (the output is pEF1). When the loop exits, the allocation is pEF1 for the current prices.
Proof. If it exits in line L3, this is the test of that line. Otherwise it exits in line L11 after a rise with . Write for the prices before the rise, for the prices after it, and for the least spending before it. Every agent of had spending at least and now has times its old spending, so at least . Every agent keeps its spending, which is at least . So the new least spending is , reached by the old least spenders.
Now check every agent . If , its spending minus its most expensive good is unchanged and at most by the definition of . If , the proof of Lemma 3 gave , and all prices of were multiplied by , so . Hence the allocation is pEF1.
Lemma 5 (pEF1 with the MBB condition gives EF1; Lemma 2 of the paper with ). If satisfies the MBB condition and is pEF1 for prices , then is EF1.
Proof. Fix agents with , and let be a most expensive good of . For any set , , and by the MBB condition . pEF1 gives . So .
Lemma 6 (MBB condition gives Pareto optimality; the first welfare theorem). If satisfies the MBB condition for prices , then no fractional allocation has for every agent with strict inequality for some agent.
Proof. Suppose is such an allocation, where is the share of good given to and . For each agent, , and with . So for every agent, with strict inequality for the agent that is strictly better off. Summing over the agents gives , a contradiction.
Theorem. If the algorithm returns an allocation, the allocation contains every good once, is EF1, and is Pareto optimal, even against fractional allocations.
Proof. Line L1 gives every good to one agent, and swaps move goods between agents, so every good stays in exactly one bundle. By Lemma 1 the prices are positive, by Lemma 2 the MBB condition holds, and by Lemma 4 the output is pEF1. Lemma 5 gives EF1 and Lemma 6 gives Pareto optimality, since an integral allocation is a special fractional one.
Termination of the exact form is not proved here. Barman, Krishnamurthy and Vaish prove that the rounded form ends in time and that, for their choice of , its output is EF1 and PO for the original values (Lemmas 3 to 5 and Theorem 1 of their paper).
Complexity
One step, a swap or a price rise, costs time: the MBB sets, the BFS of line L4 and the three bounds each read the value table once. The paper bounds the number of steps for the rounded form by , and its choice of makes the whole run pseudo-polynomial, (Theorem 1). When values are bounded by a polynomial in and , this is polynomial time (Remark 1). With exact rational arithmetic, as in the exact form, the bit length of the prices also matters. On 2000 random instances with 2 to 5 agents, 2 to 10 goods and integer values from 1 to 30, the exact form ended after at most 18 swaps and rises (measurement).
Properties
- EF1 and PO, and in fact fractionally PO: no fractional allocation is better for some agent and worse for none (Theorem 2 of the paper states that EF1 and fPO allocations always exist).
- Market equilibrium. The output with its prices is an equilibrium of a Fisher market in which each agent's budget is its final spending.
- Approximate Nash welfare. A version of the same algorithm gives an approximation of the maximum Nash welfare (Theorem 3).
- Approximate inputs run fast. For -EF1 and -PO, the time is (Remark 2).
- Deterministic. Ties are broken by index.
Variants and improvements
- Fixed number of agents. Mahara (2024) gives a polynomial-time algorithm for EF1 and fPO when is fixed, by adding agents one at a time.
- Maximum Nash welfare. For small instances, an exact MNW allocation, for example from a mixed integer program, also gives EF1 and PO.
- Divisible goods. For divisible goods, the market equilibrium with equal budgets, computed for example by the DPSV algorithm, is envy-free and PO.
When to use it
Use it when valuations are additive with small integer values, for example points that each agent spreads over the goods, and both EF1 and Pareto optimality are needed with a proof. For large instances where only EF1 is needed, round-robin allocation is simpler. When the Nash welfare itself matters, compute MNW directly if the instance is small.
Pitfalls
- A single least spender with ties in the exact form. If line L4 starts the hierarchy from only one least spender when several exist, then for a tied agent outside , the rise of line L10 changes nothing, and the loop can stall. Starting from all least spenders, as here, avoids this; the paper avoids it by its order on agents and its margins.
- Breaking on or . Line L11 may stop only when the rise reached . A rise that stopped at or has not balanced the spending, and the output need not be pEF1.
- Raising prices of goods outside . Line L10 must scale exactly the goods owned by agents of . Scaling more breaks the MBB condition of agents outside ; scaling less breaks it inside .
- Swapping across a level. In line L5 the good must go from a level- agent to an agent at level for which it is an MBB good. Moving a good to an agent that does not see it as an MBB good destroys the MBB condition and with it Pareto optimality.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ef1-and-pareto-optimal-algorithm/. The authors are listed in prov/HCYFF2.jsonl.
from fractions import Fraction
from typing import Optional, Sequence
def bundles_of(owner: Sequence[int], n: int) -> list[list[int]]:
bundles: list[list[int]] = [[] for _ in range(n)]
for j, k in enumerate(owner):
bundles[k].append(j)
return bundles
def is_price_ef1(bundles: Sequence[Sequence[int]], p: Sequence[Fraction]) -> bool:
"""pEF1: for all agents i and k, p(x_i) >= p(x_k) - p_j for some good j of x_k."""
spend = [sum((p[j] for j in b), Fraction(0)) for b in bundles]
n = len(bundles)
for k in range(n):
if not bundles[k]:
continue
reduced = spend[k] - max(p[j] for j in bundles[k])
if any(i != k and spend[i] < reduced for i in range(n)):
return False
return True
def bkv_exact(values: Sequence[Sequence], max_steps: int = 100000, stats: Optional[dict] = None) -> list[list[int]]:
"""Barman, Krishnamurthy and Vaish's market algorithm, exact variant (epsilon = 0).
values[i][j] is the additive value of agent i for good j, a positive
integer or Fraction (every value must be > 0). Returns the bundles of an
allocation that is EF1 and Pareto optimal. If stats is a dict, it gets
the final prices ("prices"), the numbers of swaps ("swaps") and of
price rises ("rises"), and a list "trace" of the events, each a tuple
(kind, owner of each good, prices) with kind "start", "swap" or "rise".
The original algorithm rounds the values to powers of (1 + epsilon) and
has a pseudo-polynomial bound for that version. Here epsilon = 0, all
least spenders are sources of the hierarchy, and every number is an
exact Fraction. When the function returns, the allocation is EF1 and
PO; no bound on the number of steps is proved for epsilon = 0, so the
loop stops with RuntimeError after max_steps swaps and rises. One step
costs O(n m) time.
"""
v = [[Fraction(x) for x in row] for row in values]
n = len(v)
if n == 0:
raise ValueError("at least one agent is needed")
m = len(v[0])
if any(len(row) != m for row in v) or any(x <= 0 for row in v for x in row):
raise ValueError("every agent needs a positive value for every good")
owner = [max(range(n), key=lambda k: (v[k][j], -k)) for j in range(m)] # @line L1
p = [v[owner[j]][j] for j in range(m)]
swaps = rises = 0
trace = stats.setdefault("trace", []) if stats is not None else None
if trace is not None:
trace.append(("start", list(owner), list(p)))
while True: # @line L2
if swaps + rises > max_steps:
raise RuntimeError("step limit reached")
x = bundles_of(owner, n)
if is_price_ef1(x, p): # @line L3
break
spend = [sum((p[j] for j in x[i]), Fraction(0)) for i in range(n)]
ratio = [max(v[i][j] / p[j] for j in range(m)) for i in range(n)]
mbb = [[j for j in range(m) if v[i][j] / p[j] == ratio[i]] for i in range(n)]
pmin = min(spend)
level = {i: 0 for i in range(n) if spend[i] == pmin} # @line L4
layers = [sorted(level)]
while layers[-1]:
nxt = set()
for g in layers[-1]:
for j in mbb[g]:
h = owner[j]
if h not in level:
level[h] = len(layers)
nxt.add(h)
layers.append(sorted(nxt))
swap = None
for depth in range(1, len(layers)): # @line L5
for h in layers[depth]:
for j in x[h]:
parents = [g for g in layers[depth - 1] if j in mbb[g]]
if parents and spend[h] - p[j] > pmin:
swap = (j, parents[0])
break
if swap:
break
if swap:
break
if swap:
owner[swap[0]] = swap[1] # @line L6
swaps += 1
if trace is not None:
trace.append(("swap", list(owner), list(p)))
continue
tree = set(level)
owned = [j for j in range(m) if owner[j] in tree]
outside = [j for j in range(m) if owner[j] not in tree]
cands1 = [ratio[h] * p[j] / v[h][j] for h in tree for j in outside]
alpha1 = min(cands1) if cands1 else None # @line L7
rest = [k for k in range(n) if k not in tree]
if pmin > 0:
alpha2 = max((spend[k] - max(p[j] for j in x[k]) if x[k] else Fraction(0)) for k in rest) / pmin # @line L8
alpha3 = min(spend[k] for k in rest) / pmin # @line L9
else:
alpha2 = alpha3 = None
alpha = min(a for a in (alpha1, alpha2, alpha3) if a is not None) # @line L10
for j in owned:
p[j] *= alpha
rises += 1
if trace is not None:
trace.append(("rise", list(owner), list(p)))
if alpha == alpha2: # @line L11
break
if stats is not None:
stats["prices"] = list(p)
stats["swaps"] = swaps
stats["rises"] = rises
return bundles_of(owner, n) # @line L12
test_ef1_and_pareto_optimal_algorithm.py 137 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ef1-and-pareto-optimal-algorithm/. The authors are listed in prov/HCYFF2.jsonl.
import itertools
import random
from fractions import Fraction
import pytest
from ef1_and_pareto_optimal_algorithm import bkv_exact, bundles_of, is_price_ef1
F = Fraction
def value(row, bundle):
return sum(row[g] for g in bundle)
def is_ef1(values, bundles) -> bool:
n = len(values)
for i in range(n):
mine = value(values[i], bundles[i])
for k in range(n):
if i != k and bundles[k]:
other = value(values[i], bundles[k])
if not any(mine >= other - values[i][g] for g in bundles[k]):
return False
return True
def is_pareto_optimal(values, bundles) -> bool:
"""Brute force over all n^m allocations."""
n, m = len(values), len(values[0])
u = [value(values[i], bundles[i]) for i in range(n)]
for owner in itertools.product(range(n), repeat=m):
w = [0] * n
for g, i in enumerate(owner):
w[i] += values[i][g]
if all(w[i] >= u[i] for i in range(n)) and any(w[i] > u[i] for i in range(n)):
return False
return True
def holds_only_mbb_goods(values, owner, p) -> bool:
n, m = len(values), len(values[0])
for i in range(n):
best = max(F(values[i][j]) / p[j] for j in range(m))
if any(owner[j] == i and F(values[i][j]) / p[j] != best for j in range(m)):
return False
return True
def test_worked_example():
values = [[5, 8, 1, 6], [3, 1, 2, 2], [1, 5, 4, 4]]
stats = {}
bundles = bkv_exact(values, stats=stats)
events = [(kind, owner, [str(q) for q in p]) for kind, owner, p in stats["trace"]]
assert events == [
("start", [0, 0, 2, 0], ["5", "8", "4", "6"]),
("swap", [1, 0, 2, 0], ["5", "8", "4", "6"]),
("rise", [1, 0, 2, 0], ["5", "8", "5", "6"]),
("rise", [1, 0, 2, 0], ["6", "8", "6", "6"]),
]
assert bundles == [[1, 3], [0], [2]]
assert [value(values[i], bundles[i]) for i in range(3)] == [14, 3, 4]
assert is_ef1(values, bundles)
assert is_pareto_optimal(values, bundles)
def test_two_agents_with_a_tie():
values = [[1, 3, 2], [1, 1, 1]]
stats = {}
assert bkv_exact(values, stats=stats) == [[1, 2], [0]]
assert [kind for kind, _, _ in stats["trace"]] == ["start", "swap", "rise"]
assert stats["prices"] == [2, 3, 2]
def test_random_ef1_and_pareto_optimal():
rng = random.Random(31)
count = 0
while count < 700:
n = rng.randint(2, 4)
m = rng.randint(1, 6 if n < 4 else 5)
top = rng.choice([2, 4, 10, 30])
values = [[rng.randint(1, top) for _ in range(m)] for _ in range(n)]
stats = {}
bundles = bkv_exact(values, stats=stats)
assert sorted(g for b in bundles for g in b) == list(range(m))
assert is_ef1(values, bundles)
assert is_pareto_optimal(values, bundles)
count += 1
def test_invariants_along_the_run():
rng = random.Random(32)
for _ in range(400):
n, m = rng.randint(2, 5), rng.randint(2, 9)
values = [[rng.randint(1, 12) for _ in range(m)] for _ in range(n)]
stats = {}
bundles = bkv_exact(values, stats=stats)
last = None
for kind, owner, p in stats["trace"]:
assert holds_only_mbb_goods(values, owner, p)
if last is not None:
assert all(a >= b for a, b in zip(p, last))
if kind == "rise":
assert any(a > b for a, b in zip(p, last))
last = p
assert is_price_ef1(bundles, stats["prices"])
assert is_ef1(values, bundles)
def test_one_agent_and_identical_values():
assert bkv_exact([[3, 1, 2]]) == [[0, 1, 2]]
rng = random.Random(33)
for _ in range(100):
n, m = rng.randint(2, 4), rng.randint(1, 7)
row = [rng.randint(1, 9) for _ in range(m)]
values = [row] * n
assert is_ef1(values, bkv_exact(values))
def test_price_ef1_check():
p = [F(5), F(8), F(4), F(6)]
assert not is_price_ef1(bundles_of([0, 0, 2, 0], 3), p)
assert is_price_ef1([[1, 3], [0], [2]], [F(6), F(8), F(6), F(6)])
def test_bad_input_and_step_limit():
with pytest.raises(ValueError):
bkv_exact([])
with pytest.raises(ValueError):
bkv_exact([[1, 0], [1, 1]])
with pytest.raises(ValueError):
bkv_exact([[1, 2], [1]])
with pytest.raises(RuntimeError):
bkv_exact([[5, 8, 1, 6], [3, 1, 2, 2], [1, 5, 4, 4]], max_steps=0)
History
Barman, Krishnamurthy and Vaish presented the algorithm at EC 2018 (arXiv 2017). They write that establishing its running time is an intricate task, which their analysis does for the rounded instance. Before it, the only general route to EF1 and PO was maximum Nash welfare, from Caragiannis et al. (EC 2016), which is NP-hard to compute.
References
- Siddharth Barman, Sanath Kumar Krishnamurthy and Rohit Vaish, Finding fair and efficient allocations, Proceedings of the 19th ACM Conference on Economics and Computation (EC 2018), 557-574 (arXiv:1707.04731), Section 4 (hierarchy, violators and path-violators, Algorithm 1 with its three phases), Lemma 2 (pEF1 with MBB gives EF1), Lemmas 3 to 5, Theorems 1 to 3 and Remarks 1 and 2
- Ryoga Mahara, A polynomial-time algorithm for fair and efficient allocation with a fixed number of agents, arXiv:2411.01810 (November 2024), abstract (the open problem of polynomial time, and the algorithm for a fixed number of agents)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag HCYFF2 Edit this page History Report an error Markdown