Algorithm Search⌘K

Algorithmadvanced

Recognizing single-peaked profiles

Also called Bartholdi-Trick algorithm, Escoffier-Lang-Ozturk algorithm, single-peaked consistency.

Decides whether a profile is single-peaked on some ordering of the candidates, and finds such an axis, in O(mn) time by placing candidates from the two ends inward.

Time
O(m n) worst
Space
O(m n) extra
Where
m = the number of candidates; n = the number of voters
Properties
not comparison baseddeterministiciterative
Origin
John J. Bartholdi III, Michael A. Trick, Jean Paul Doignon, Jean Claude Falmagne, Bruno Escoffier, Jérôme Lang, Meltem Öztürk, 1986

Recognizing single-peaked profiles is the problem of deciding whether a preference profile is single-peaked on some order of the candidates, and of finding such an order, the axis. The axis is not part of the input, and there are m!m! candidate orders, so a search over all of them is hopeless beyond tiny cases. The algorithm on this page fills the axis from both ends toward the middle: the candidates that voters rank last must go at the ends. It runs in O(mn)O(mn) time for nn voters and mm candidates, which is linear in the size of the profile.

In plain words

In a single-peaked profile, the worst candidate of every voter is at one of the two ends of the line, because every voter likes candidates less as they move away from the favourite. So look at the bottom of every ballot. If three or more different candidates appear there, no line works. If one or two appear, put them at the free ends of the line, delete them from all ballots, and repeat with the rest. The only care needed is to choose the correct end for each candidate. A voter who likes the new candidate more than the candidate at one end and less than the candidate at the other end tells you which end is correct.

The problem

The input is a profile P=(≻1,…,≻n)P = (\succ_1, \ldots, \succ_n) of strict rankings of the candidates A={0,…,m−1}A = \{0, \ldots, m - 1\}, each ranking stored as a list, best first. The output is an axis ⊲\lhd, a linear order of AA, such that each ≻i\succ_i is single-peaked on ⊲\lhd, or NONE if no such axis exists. If an axis exists, its reverse also works, and there may be many more.

The key facts are from the definition. On a single-peaked profile, each voter's last candidate is an end of the axis, so at most two candidates are last for some voter. Removing candidates keeps the profile single-peaked on the restricted axis. Together they suggest the outside-in method, but they do not tell which end a candidate should go to. The test in lines L10 and L11 answers this.

The algorithm

  1. SP-AXIS(P, m) ▷ P = (≻_1, ..., ≻_n), candidates 0, ..., m - 1
  2. 1pos_i[a] ← position of a in ≻_i, for each voter i and candidate a
  3. 2left ← (); right ← (); R ← all candidates ▷ R: the unplaced candidates
  4. 3while |R| ≥ 2 do
  5. 4B ← {the candidate that voter i ranks last in R : i = 1, ..., n}
  6. 5if |B| ≥ 3 then return NONE
  7. 6if right is empty then ▷ first stage: fill both ends
  8. 7append min B to left; if |B| = 2 then append max B to right
  9. 8else ▷ second stage
  10. 9ℓ ← innermost candidate of left; r ← innermost candidate of right
  11. 10L ← {x in B : some voter i who does not rank x first in R has r ≻_i x ≻_i ℓ}
  12. 11R' ← {x in B : some voter i who does not rank x first in R has ℓ ≻_i x ≻_i r}
  13. 12if |L| ≥ 2 or |R'| ≥ 2 or L ∩ R' ≠ ∅ then return NONE
  14. 13put each x in B that is in neither set into L if L is empty, else into R'
  15. 14append L to left; append R' to right
  16. 15R ← R \ B; move each voter's first and last pointers past placed candidates
  17. 16return left, then R, then right from the outer end inward

Line L1 makes every comparison a≻iba \succ_i b a comparison of two stored integers. Lines L4 and L5 find the candidates ranked last in the remaining set. In the first stage, line L7 fills the left end, and the right end as soon as two candidates are ranked last. In the second stage a candidate xx goes next to ℓ\ell if a voter ranks xx between rr above and ℓ\ell below while preferring some other remaining candidate to xx: putting xx next to rr would make a valley at xx for that voter. Line L11 is the mirror test. The free choices in lines L7 and L13 put the smaller candidate on the left.

Example

Take five candidates a,b,c,d,ea, b, c, d, e, numbered 00 to 44, and three voters (Elkind, Lackner and Peters, Example 26):

≻1=e d b c a,≻2=e d c b a,≻3=d e c a b.\succ_1 = e\,d\,b\,c\,a, \qquad \succ_2 = e\,d\,c\,b\,a, \qquad \succ_3 = d\,e\,c\,a\,b.
round RR last candidates BB ℓ\ell, rr decision partial axis
1 {a,b,c,d,e}\{a, b, c, d, e\} {a,b}\{a, b\} none first stage: aa left, bb right a…ba \ldots b
2 {c,d,e}\{c, d, e\} {c}\{c\} aa, bb voter 1 has b≻c≻ab \succ c \succ a and prefers ee to cc, so c∈Lc \in L a c…ba\,c \ldots b
3 {d,e}\{d, e\} {d,e}\{d, e\} cc, bb no voter constrains dd or ee, so dd goes left and ee right a c d e ba\,c\,d\,e\,b

The loop stops with RR empty, and line L16 returns a⊲c⊲d⊲e⊲ba \lhd c \lhd d \lhd e \lhd b. All three rankings are single-peaked on it: voter 3, for example, has peak dd and goes down to cc, aa on the left and to ee, bb on the right. If round 2 had put cc next to bb, then voter 1 would have a valley at cc between ee and bb. The axes for this profile are a c d e ba\,c\,d\,e\,b, a c e d ba\,c\,e\,d\,b and their reverses.

Correctness

The proof is in proofs/correctness.md, after Elkind, Lackner and Peters (Theorem 4.2). It has two parts.

If the algorithm returns an axis, suppose some voter had a valley on it. Then there is a valley on three adjacent candidates a,b,ca, b, c. The first of them to be placed is an end one, say aa, and it was placed in a round with two last candidates. The middle one bb is placed no later than cc. When bb is placed, the voter ranks it below a=ℓa = \ell and, by a lemma on the earlier rounds, above rr. The voter also prefers cc to bb. So line L11 forces bb next to rr, not next to aa, which is a contradiction.

If the algorithm returns NONE, the proof finds one of two small patterns that no single-peaked profile can contain: three candidates that are each ranked below the other two by some voter, or four candidates with two voters whose top two sets cannot both be intervals of any axis.

Proof: The outside-in algorithm returns an axis exactly when the profile is single-peakedfull

The proof follows the structure of Elkind, Lackner and Peters (survey, Theorem 4.2), with the free choices of the code fixed and with the case analysis of the second claim done in full. Let P=(≻1,…,≻n)P = (\succ_1, \ldots, \succ_n) be a profile of strict rankings of AA, ∣A∣=m|A| = m, n≥1n \ge 1. We use the no-valley form of single-peakedness: a ranking ≻\succ is single-peaked on an axis ⊲\lhd if and only if there are no a⊲b⊲ca \lhd b \lhd c with a≻ba \succ b and c≻bc \succ b. Such a triple is a valley at bb.

Notation. In a round, RR is the set of unplaced candidates, BB is the set of candidates that some voter ranks last in RR (line L4), and NxN_x is the set of voters who do not rank xx first in RR. In the second stage, when the right list is not empty, ℓ\ell is the innermost candidate on the left and rr the innermost on the right (line L9), and lines L10 and L11 compute

L={x∈B:∃i∈Nx, r≻ix≻iℓ},R′={x∈B:∃i∈Nx, ℓ≻ix≻ir}.L = \{x \in B : \exists i \in N_x,\ r \succ_i x \succ_i \ell\}, \qquad R' = \{x \in B : \exists i \in N_x,\ \ell \succ_i x \succ_i r\}.

Elements of LL go next to ℓ\ell and elements of R′R' next to rr. Line L13 puts each free element of BB on a side that is still free, the left first.

Facts about rounds.

  1. Each round puts at most one candidate at the inner end of each list, so the placed candidates are a prefix and a suffix of the final axis and RR is the gap between them. Line L16 joins left, gap and right.
  2. If ∣B∣=1|B| = 1, its element is a unanimous bottom: every voter ranks it last in RR.
  3. If ∣B∣=2|B| = 2, its two elements go to opposite sides: by line L7 in the first stage, and in the second stage because line L12 rejects ∣L∣≥2|L| \ge 2, ∣R′∣≥2|R'| \ge 2 and L∩R′≠∅L \cap R' \ne \emptyset.
  4. Every candidate placed in a round is ranked last in that round's RR by some voter.

Lemma 1. In a round of the second stage, let x∈Rx \in R. Every voter ranks xx above ℓ\ell or above rr.

Proof. If ℓ\ell and rr were placed in the same round, then BB was {ℓ,r}\{\ell, r\} in that round and every voter ranked one of them last in a set that contains xx. If rr was placed in a later round than ℓ\ell, nothing was put on the left in that later round, because ℓ\ell is still the innermost left candidate. So that round had B={r}B = \{r\}, a unanimous bottom, and every voter ranks xx above rr. The case where ℓ\ell was placed later is the mirror image. □\square

Claim 1: if the code returns an axis, every ranking is single-peaked on it

Suppose voter ii has a valley on the output axis. Then it has one on three adjacent candidates: if a⊲a′⊲ba \lhd a' \lhd b with a,b,ca, b, c a valley at bb, then either a′≻iba' \succ_i b and a′,b,ca', b, c is a narrower valley, or b≻ia′b \succ_i a' and a,a′,ba, a', b is one. So let a,b,ca, b, c be adjacent on the axis, in this order, with a≻iba \succ_i b and c≻ibc \succ_i b. Look at the first round that places one of them.

  • Two of them on the same side in one round is impossible by fact 1. Exactly aa and cc is impossible: bb would be in RR, voter ii ranks it below both, so the voter's bottom in RR is a third element of BB. Exactly bb is impossible, because bb lies strictly inside the gap.
  • So the round places exactly one of aa and cc; by the mirror image we may assume it is aa. If ∣B∣=1|B| = 1 in that round, aa is a unanimous bottom of a set that contains bb, which contradicts a≻iba \succ_i b. So ∣B∣=2|B| = 2 and all later rounds are in the second stage.
  • Suppose cc is placed strictly before bb. At that round aa is placed and b,cb, c are not, the gap is an interval, and cc is at its end, so the gap is {b,c}\{b, c\}. Voter ii ranks bb last in it, so b∈Bb \in B and bb is placed in the same round as cc, a contradiction.
  • So bb is placed while cc is still in RR, and it is put next to aa, so ℓ=a\ell = a in that round. By Lemma 1, voter ii ranks bb above ℓ=a\ell = a or above rr; the first is false, so a≻ib≻ira \succ_i b \succ_i r. Voter ii ranks c∈Rc \in R above bb, so i∈Nbi \in N_b and b∈R′b \in R'. Since line L12 did not stop, b∉Lb \notin L, and line L14 puts bb next to rr, not next to aa. This is a contradiction. □\square

Claim 2: if the code returns NONE, the profile is not single-peaked

Lemma 2. (a) If each of three candidates is ranked below the other two by some voter, PP is not single-peaked. (b) If there are candidates a,b,c,da, b, c, d and voters i,ji, j with {a,d}≻ib≻ic\{a, d\} \succ_i b \succ_i c and {c,d}≻jb≻ja\{c, d\} \succ_j b \succ_j a, then PP is not single-peaked.

Proof. (a) On any axis one of the three lies between the other two, and the voter who ranks it last has a valley there. (b) Restrict to {a,b,c,d}\{a, b, c, d\}; this keeps single-peakedness. The top two candidates of a single-peaked ranking form an interval, so {a,d}\{a, d\} and {c,d}\{c, d\} are intervals, and the last candidates cc of ii and aa of jj are the two ends. So the axis is a,⋅,⋅,ca, \cdot, \cdot, c with bb and dd in the middle. If bb is next to aa, then {a,d}\{a, d\} is not an interval; if dd is next to aa, then {c,d}\{c, d\} is not one. □\square

The code returns NONE only at line L5 or at line L12.

Line L5. Three elements of BB are each last in RR for some voter, which is Lemma 2(a).

∣L∣≥2|L| \ge 2 at line L12. Let a,b∈La, b \in L with voters i∈Nai \in N_a, r≻ia≻iℓr \succ_i a \succ_i \ell, and j∈Nbj \in N_b, r≻jb≻jℓr \succ_j b \succ_j \ell. The candidate rr was placed in an earlier round, so by fact 4 some voter tt ranks rr below every candidate of RR, in particular below aa and bb. By Lemma 2(a) on {a,b,r}\{a, b, r\} it suffices to find a voter who ranks aa last in this triple and one who ranks bb last in it.

Voter ii ranks aa below rr. If b≻iab \succ_i a, voter ii ranks aa last in the triple; if a≻iba \succ_i b, it ranks bb last. Voter jj in the same way ranks bb last if a≻jba \succ_j b and aa last if b≻jab \succ_j a. If the two voters give different answers, we are done. Otherwise, by the symmetry between (a,i)(a, i) and (b,j)(b, j), assume both rank bb last, so r≻ia≻ibr \succ_i a \succ_i b. Since i∈Nai \in N_a, the top xx of voter ii in RR is not aa, and it is not bb, so {x,r}≻ia≻ib\{x, r\} \succ_i a \succ_i b. Since a∈Ba \in B, some voter kk ranks aa last in RR, so {x,b}≻ka\{x, b\} \succ_k a. If r≻kar \succ_k a, voter kk ranks aa last in the triple and we are done. If a≻kra \succ_k r, then {r,x}≻ia≻ib\{r, x\} \succ_i a \succ_i b and {b,x}≻ka≻kr\{b, x\} \succ_k a \succ_k r, which is Lemma 2(b) with the candidates r,a,b,xr, a, b, x in the roles of a,b,c,da, b, c, d.

The case ∣R′∣≥2|R'| \ge 2 is the mirror image.

L∩R′≠∅L \cap R' \ne \emptyset at line L12. Let a∈L∩R′a \in L \cap R', with voters i,j∈Nai, j \in N_a, r≻ia≻iℓr \succ_i a \succ_i \ell and ℓ≻ja≻jr\ell \succ_j a \succ_j r. We find b∈R∖{a}b \in R \setminus \{a\} that both voters rank above aa. If ∣B∣=1|B| = 1, aa is a unanimous bottom, and any other b∈Rb \in R works (∣R∣≥2|R| \ge 2 in the loop). If B={a,b}B = \{a, b\} and, say, a≻iba \succ_i b, then i∈Nbi \in N_b and r≻ibr \succ_i b, and by Lemma 1 also b≻iℓb \succ_i \ell, so b∈Lb \in L and ∣L∣=2|L| = 2; that case is done above. The same holds for jj with R′R'. So b≻iab \succ_i a and b≻jab \succ_j a, and

{r,b}≻ia≻iℓ,{ℓ,b}≻ja≻jr,\{r, b\} \succ_i a \succ_i \ell, \qquad \{\ell, b\} \succ_j a \succ_j r,

which is Lemma 2(b) with r,a,ℓ,br, a, \ell, b in the roles of a,b,c,da, b, c, d. □\square

Running time

Line L1 builds the table of positions in O(mn)O(mn) time. Each round places one or two candidates, so there are at most mm rounds. In a round, line L4 reads one bottom pointer per voter, lines L10 and L11 make at most 2n2n constant-time comparisons, and line L15 moves the pointers past placed candidates. Each pointer moves at most mm times in the whole run. The total is O(mn)O(mn) time and O(mn)O(mn) space.

The tests in impl/python/test_single_peaked_recognition.py compare the answer with a search over all m!m! axes on every profile of up to 3 voters on 3 candidates and of 2 voters on 4 candidates, and on random profiles with up to 6 candidates, and they check every returned axis.

Complexity

Line L1 takes O(mn)O(mn) time. There are at most mm rounds, because each round places one or two candidates. Each voter keeps a pointer to its first and its last remaining candidate, so line L4 costs O(n)O(n), lines L10 and L11 make at most 2n2n comparisons of positions, and line L15 moves each pointer at most mm times in the whole run. The total is O(mn)O(mn) time in the word RAM model, linear in the input, and O(mn)O(mn) extra space for the position table. If rankings were searched by scanning, each comparison would cost O(m)O(m) and the bound would be O(m2n)O(m^2 n).

Properties

  • Exact. It returns an axis exactly when one exists, and every returned axis works.
  • One axis, not all. The output is one axis. The set of all axes has a compact form; a PQ-tree built by the consecutive ones method describes all of them, and Elkind, Lackner and Peters (Section 4.1) give a direct description of the set.
  • Deterministic. With the fixed choices in lines L7 and L13 the output depends only on the input.
  • Not neutral in its output. Renaming the candidates can give a different axis among the valid ones, because free choices go by index.
  • The answer is a certificate. A returned axis can be checked in O(mn)O(mn) time with the interval test of the definition; a NONE answer comes with one of the two forbidden patterns in the proof.

Variants and improvements

  • Consecutive ones. Bartholdi and Trick (1986) wrote one 0-1 row for each top-kk set of each voter, nmnm rows over mm columns, and asked for a column order with the ones of every row consecutive, the consecutive ones property. The matrix has Θ(m2n)\Theta(m^2 n) entries, so this route takes O(m2n)O(m^2 n) time, and its PQ-tree gives all axes at once.
  • Direct algorithms. Doignon and Falmagne (1994) gave a direct algorithm in O(mn+m2)O(mn + m^2) time, and Escoffier, Lang and Ozturk (2008) one in O(mn)O(mn) time. The form on this page follows the survey of Elkind, Lackner and Peters.
  • Other domains. Single-crossing profiles can be recognized in O(nmlog⁡m)O(nm \log m) time and one-dimensional Euclidean profiles in polynomial time, while for dd-dimensional Euclidean preferences with a fixed d≥2d \ge 2 recognition is NP-hard (survey, Theorems 4.8, 4.11 and 4.12).
  • Nearly single-peaked profiles. Deleting the fewest candidates to make a profile single-peaked takes polynomial time, O(m3n)O(m^3 n), while deleting the fewest voters is NP-complete (survey, Section 4.8, Table 2).

When to use it

Use it before you rely on any result that needs single-peakedness: the median voter theorem, the strategyproof generalized median voter rules, or the polynomial algorithm for the Chamberlin-Courant rule on single-peaked profiles, which needs the axis as input. If the axis is known from the problem, such as a numerical scale, check the profile against it directly with the interval test instead.

Pitfalls

  • Checking each voter alone. Every single ranking is single-peaked on some axis. The question is whether one axis works for all voters.
  • Choosing the side without the test. In round 2 of the example, cc can go next to aa or next to bb as far as the end positions go, but only the first choice works. A rule such as "always the left side" works in the first stage and fails in the second, where lines L10 and L11 decide.
  • Slow comparisons. Lines L10 and L11 compare positions. Looking a candidate up in a list costs O(m)O(m) and raises the time to O(m2n)O(m^2 n).
  • Ties and missing candidates. The algorithm needs strict and complete rankings. Weak orders and partial rankings need other algorithms.

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.

agtprefs.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the algorithmic game theory pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Preference profiles, majority relations and brute force axiom checkers.

The candidates are 0, ..., m - 1. A ranking is a tuple of all m candidates, best first:
(2, 0, 1) means that 2 is preferred to 0 and 0 to 1. A profile is a tuple of n rankings,
one per voter. An approval ballot is a frozenset of candidates, and an approval profile is
a tuple of n ballots.

A rule is a function rule(profile, m). A resolute rule returns one candidate (an int); a
correspondence returns a nonempty frozenset of candidates. The checkers accept both: they
turn an int w into frozenset({w}).

Each checker takes the rule, m and n, and by default tries every profile of all_profiles(m,
n). Pass profiles= to check a given list of profiles instead (for example approval profiles,
or a random sample when the full domain is too large). Each checker returns None when the
property holds on every profile it tried, and else a counterexample tuple.

There is no voting rule in this module. Every count is an exact integer.
"""

from itertools import permutations, product


# ---------------------------------------------------------------- rankings and profiles


def all_rankings(m):
    """Return the list of the m! rankings of 0, ..., m - 1, in lexicographic order."""
    return list(permutations(range(m)))


def all_profiles(m, n):
    """Yield every profile of n rankings of m candidates: (m!)^n profiles, voters ordered."""
    return product(all_rankings(m), repeat=n)


def random_profile(rng, m, n):
    """Return a profile of n rankings drawn uniformly and independently (impartial culture)."""
    return tuple(tuple(rng.sample(range(m), m)) for _ in range(n))


def position(r, a):
    """Return the position of candidate a in ranking r: 0 for the top."""
    return r.index(a)


def prefers(r, a, b):
    """Return True if ranking r puts a above b."""
    return r.index(a) < r.index(b)


def pairwise(profile, m):
    """Return the m by m matrix N with N[a][b] the number of voters who rank a above b."""
    N = [[0] * m for _ in range(m)]
    for r in profile:
        for i, a in enumerate(r):
            for b in r[i + 1:]:
                N[a][b] += 1
    return N


def margins(profile, m):
    """Return the m by m matrix of margins N[a][b] - N[b][a]."""
    N = pairwise(profile, m)
    return [[N[a][b] - N[b][a] for b in range(m)] for a in range(m)]


def condorcet_winner(profile, m):
    """Return the candidate with a positive margin over every other candidate, or None."""
    M = margins(profile, m)
    for a in range(m):
        if all(M[a][b] > 0 for b in range(m) if b != a):
            return a
    return None


def weak_condorcet_winners(profile, m):
    """Return the frozenset of candidates whose margin over every other candidate is >= 0."""
    M = margins(profile, m)
    return frozenset(a for a in range(m) if all(M[a][b] >= 0 for b in range(m) if b != a))


def kendall_tau(r1, r2):
    """Return the number of pairs of candidates that r1 and r2 order differently."""
    pos = {a: i for i, a in enumerate(r2)}
    seq = [pos[a] for a in r1]
    return sum(1 for i in range(len(seq)) for j in range(i + 1, len(seq)) if seq[i] > seq[j])


def is_single_peaked_on(profile, axis):
    """Return True if every ranking of the profile is single-peaked on the axis.

    axis is a tuple of all candidates, left to right. A ranking is single-peaked on the axis
    exactly when, for each k, its k best candidates form a contiguous block of the axis.
    """
    where = {a: i for i, a in enumerate(axis)}
    for r in profile:
        lo = hi = where[r[0]]
        for a in r[1:]:
            p = where[a]
            if p == lo - 1:
                lo = p
            elif p == hi + 1:
                hi = p
            else:
                return False
    return True


def lex_tiebreak(candidates):
    """Return the candidate with the smallest index: the default tie-breaking rule."""
    return min(candidates)


def random_approval_profile(rng, m, n, p):
    """Return n approval ballots; each voter approves each candidate with probability p."""
    return tuple(frozenset(a for a in range(m) if rng.random() < p) for _ in range(n))


def permute_profile(profile, pi):
    """Rename the candidates: candidate a becomes pi[a]. Works for rankings and approval ballots."""
    out = []
    for ballot in profile:
        if isinstance(ballot, (set, frozenset)):
            out.append(frozenset(pi[a] for a in ballot))
        else:
            out.append(tuple(pi[a] for a in ballot))
    return tuple(out)


# ---------------------------------------------------------------- axiom checkers


def _as_set(result):
    if isinstance(result, (set, frozenset)):
        return frozenset(result)
    return frozenset([result])


def _domain(m, n, profiles):
    return all_profiles(m, n) if profiles is None else profiles


def _candidate_generators(m):
    """A transposition and an m-cycle: together they generate every permutation of the candidates."""
    gens = []
    if m >= 2:
        swap = list(range(m))
        swap[0], swap[1] = 1, 0
        gens.append(tuple(swap))
    if m >= 3:
        gens.append(tuple((a + 1) % m for a in range(m)))
    return gens


def check_anonymity(rule, m, n, profiles=None):
    """Check that permuting the voters does not change the result.

    It tries the swap of voters 0 and 1 and the cyclic shift of the voters. These generate all
    permutations, so on the full domain this is a complete test. Returns None or
    (profile, permuted_profile).
    """
    for P in _domain(m, n, profiles):
        P = tuple(P)
        if len(P) < 2:
            continue
        base = _as_set(rule(P, m))
        others = [(P[1], P[0]) + P[2:], P[1:] + P[:1]]
        for Q in others:
            if _as_set(rule(Q, m)) != base:
                return (P, Q)
    return None


def check_neutrality(rule, m, n, profiles=None):
    """Check that renaming the candidates by pi renames the result by pi.

    It tries a transposition and an m-cycle of the candidates, which generate all permutations.
    A resolute rule with a fixed tie-breaking order usually fails this test; test its
    correspondence instead. Returns None or (profile, pi).
    """
    gens = _candidate_generators(m)
    for P in _domain(m, n, profiles):
        P = tuple(P)
        base = _as_set(rule(P, m))
        for pi in gens:
            if _as_set(rule(permute_profile(P, pi), m)) != frozenset(pi[a] for a in base):
                return (P, pi)
    return None


def check_pareto(rule, m, n, profiles=None):
    """Check that no candidate b wins when every voter ranks some a above b.

    Returns None or (profile, a, b).
    """
    for P in _domain(m, n, profiles):
        P = tuple(P)
        W = _as_set(rule(P, m))
        N = pairwise(P, m)
        for b in W:
            for a in range(m):
                if a != b and N[a][b] == len(P):
                    return (P, a, b)
    return None


def check_condorcet_consistency(rule, m, n, profiles=None):
    """Check that a Condorcet winner, when one exists, is the unique winner.

    Returns None or (profile, condorcet_winner).
    """
    for P in _domain(m, n, profiles):
        P = tuple(P)
        c = condorcet_winner(P, m)
        if c is not None and _as_set(rule(P, m)) != frozenset([c]):
            return (P, c)
    return None


def _raise_once(r, w):
    """Return r with w moved up one place, or None if w is already on top."""
    i = r.index(w)
    if i == 0:
        return None
    s = list(r)
    s[i - 1], s[i] = s[i], s[i - 1]
    return tuple(s)


def check_monotonicity(rule, m, n, profiles=None):
    """Check that a winner stays a winner when one voter moves it up one place.

    Every raise of w, with no other change in the relative order of the others, is a chain of
    such one-place moves, so on the full domain this is a complete test. For a correspondence
    the test is that w stays in the winning set. Returns None or (profile, raised_profile, w).
    """
    for P in _domain(m, n, profiles):
        P = tuple(P)
        for w in _as_set(rule(P, m)):
            for i, r in enumerate(P):
                s = _raise_once(r, w)
                if s is None:
                    continue
                Q = P[:i] + (s,) + P[i + 1:]
                if w not in _as_set(rule(Q, m)):
                    return (P, Q, w)
    return None


def find_manipulation(rule, m, n, profiles=None):
    """Search for a voter who gets a strictly better winner by a false ranking.

    The rule must be resolute (a correspondence must return one winner on every profile it
    is called on). Returns None or (profile, voter, false_ranking): with the false ranking in
    place of the voter's true one, the winner is one that the true ranking strictly prefers.
    """
    rankings = all_rankings(m)
    for P in _domain(m, n, profiles):
        P = tuple(P)
        w = _single(rule(P, m))
        for i, r in enumerate(P):
            if r[0] == w:
                continue
            for s in rankings:
                if s == r:
                    continue
                Q = P[:i] + (s,) + P[i + 1:]
                if prefers(r, _single(rule(Q, m)), w):
                    return (P, i, s)
    return None


def _single(result):
    W = _as_set(result)
    if len(W) != 1:
        raise ValueError("find_manipulation needs a resolute rule")
    return next(iter(W))
single_peaked_recognition.py 84 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/single-peaked-recognition/. The authors are listed in prov/HW79QR.jsonl.
"""Recognize single-peaked profiles and find an axis, in O(m n) time.

The candidates are 0, ..., m - 1 and a profile is a sequence of n rankings, each a tuple of all
m candidates, best first. The algorithm builds the axis from the two ends inward: at each
step the candidates that some voter ranks last among the unplaced ones must go to the free
ends. This is the algorithm of Doignon and Falmagne (1994) and Escoffier, Lang and Ozturk
(2008) in the form of Elkind, Lackner and Peters (survey, Algorithm 1).

Free choices are made in a fixed way: the smaller candidate goes to the left.
"""

from typing import Optional, Sequence

Ranking = Sequence[int]


def single_peaked_axis(profile: Sequence[Ranking], m: int) -> Optional[tuple]:
    """Return an axis (a tuple of all m candidates, left to right) on which every ranking of
    the profile is single-peaked, or None if there is no such axis."""
    n = len(profile)
    if n == 0:
        return tuple(range(m))
    pos = []
    for r in profile:  # @line L1
        p = [0] * m
        for k, a in enumerate(r):
            p[a] = k
        pos.append(p)
    top = [0] * n
    bot = [m - 1] * n
    placed = [False] * m
    left, right = [], []  # @line L2
    rest = m
    while rest >= 2:  # @line L3
        B = {profile[i][bot[i]] for i in range(n)}  # @line L4
        if len(B) >= 3:  # @line L5
            return None
        B = sorted(B)
        if not right:  # @line L6
            left.append(B[0])  # @line L7
            if len(B) == 2:
                right.append(B[1])
        else:  # @line L8
            l, r = left[-1], right[-1]  # @line L9
            to_left, to_right = set(), set()
            for x in B:
                for i in range(n):
                    if profile[i][top[i]] == x:
                        continue
                    p = pos[i]
                    if p[r] < p[x] < p[l]:
                        to_left.add(x)  # @line L10
                    if p[l] < p[x] < p[r]:
                        to_right.add(x)  # @line L11
            if len(to_left) >= 2 or len(to_right) >= 2 or to_left & to_right:  # @line L12
                return None
            free = [x for x in B if x not in to_left and x not in to_right]  # @line L13
            for x in free:
                if not to_left:
                    to_left.add(x)
                else:
                    to_right.add(x)
            left.extend(to_left)  # @line L14
            right.extend(to_right)
        for x in B:  # @line L15
            placed[x] = True
        rest -= len(B)
        if rest == 0:
            break
        for i in range(n):
            r = profile[i]
            while placed[r[bot[i]]]:
                bot[i] -= 1
            while placed[r[top[i]]]:
                top[i] += 1
    middle = [a for a in range(m) if not placed[a]]
    return tuple(left + middle + right[::-1])  # @line L16


def is_single_peaked(profile: Sequence[Ranking], m: int) -> bool:
    """Return True if the profile is single-peaked on some axis."""
    return single_peaked_axis(profile, m) is not None
test_single_peaked_recognition.py 112 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/single-peaked-recognition/. The authors are listed in prov/HW79QR.jsonl.

import itertools
import random

from agtprefs import all_profiles, all_rankings, is_single_peaked_on, random_profile
from single_peaked_recognition import is_single_peaked, single_peaked_axis


def brute_axes(profile, m):
    return [ax for ax in itertools.permutations(range(m)) if is_single_peaked_on(profile, ax)]


def random_sp_ranking(rng, axis):
    """Build a ranking single-peaked on axis from the bottom: take one end of the rest each time."""
    lo, hi = 0, len(axis) - 1
    worst_first = []
    while lo < hi:
        if rng.random() < 0.5:
            worst_first.append(axis[lo])
            lo += 1
        else:
            worst_first.append(axis[hi])
            hi -= 1
    worst_first.append(axis[lo])
    return tuple(reversed(worst_first))


def check(profile, m):
    axis = single_peaked_axis(profile, m)
    exists = bool(brute_axes(profile, m))
    assert (axis is not None) == exists, (profile, axis)
    if axis is not None:
        assert sorted(axis) == list(range(m))
        assert is_single_peaked_on(profile, axis)


def test_every_profile_with_three_candidates():
    for n in range(1, 4):
        for P in all_profiles(3, n):
            check(P, 3)


def test_every_profile_of_two_voters_with_four_candidates():
    for P in all_profiles(4, 2):
        check(P, 4)


def test_random_single_peaked_profiles_are_recognized():
    rng = random.Random(1)
    for _ in range(300):
        m = rng.randint(2, 6)
        axis = tuple(rng.sample(range(m), m))
        P = tuple(random_sp_ranking(rng, axis) for _ in range(rng.randint(1, 6)))
        check(P, m)
        assert is_single_peaked(P, m)


def test_random_profiles_agree_with_brute_force():
    rng = random.Random(2)
    for _ in range(300):
        m = rng.randint(3, 6)
        n = rng.randint(1, 4)
        if rng.random() < 0.5:
            P = random_profile(rng, m, n)
        else:
            axis = tuple(rng.sample(range(m), m))
            P = [random_sp_ranking(rng, axis) for _ in range(n)]
            i = rng.randrange(n)
            r = list(P[i])
            a, b = rng.sample(range(m), 2)
            r[a], r[b] = r[b], r[a]
            P[i] = tuple(r)
            P = tuple(P)
        check(P, m)


def test_count_of_single_peaked_rankings_on_one_axis():
    for m in range(1, 7):
        axis = tuple(range(m))
        assert sum(1 for r in all_rankings(m) if is_single_peaked_on((r,), axis)) == 2 ** (m - 1)


def test_condorcet_cycle_is_not_single_peaked():
    assert single_peaked_axis(((0, 1, 2), (1, 2, 0), (2, 0, 1)), 3) is None


def test_worked_example():
    # a, b, c, d, e = 0, 1, 2, 3, 4
    P = ((4, 3, 1, 2, 0), (4, 3, 2, 1, 0), (3, 4, 2, 0, 1))
    assert single_peaked_axis(P, 5) == (0, 2, 3, 4, 1)
    assert brute_axes(P, 5) == [(0, 2, 3, 4, 1), (0, 2, 4, 3, 1), (1, 3, 4, 2, 0), (1, 4, 3, 2, 0)]


def test_edge_cases():
    assert single_peaked_axis((), 3) == (0, 1, 2)
    assert single_peaked_axis(((0,),), 1) == (0,)
    assert single_peaked_axis(((1, 0),), 2) in ((0, 1), (1, 0))


def test_larger_profile():
    rng = random.Random(3)
    m = 40
    axis = tuple(rng.sample(range(m), m))
    P = tuple(random_sp_ranking(rng, axis) for _ in range(300))
    found = single_peaked_axis(P, m)
    assert found is not None and is_single_peaked_on(P, found)
    Q = P[:-1] + (tuple(rng.sample(range(m), m)),)
    found = single_peaked_axis(Q, m)
    if found is not None:
        assert is_single_peaked_on(Q, found)

History

Black (1948) defined single-peaked preferences, but the question of finding the axis came much later. Bartholdi and Trick (1986) met it while studying stable roommates with preferences from a one-dimensional model, and solved it by the consecutive ones property and PQ-trees. Doignon and Falmagne (1994) gave a direct algorithm in the language of unidimensional unfolding in psychology, and Escoffier, Lang and Ozturk (2008) found a direct linear algorithm independently, in computational social choice.

References

  1. John J. Bartholdi III and Michael A. Trick, Stable matching with preferences derived from a psychological model, Operations Research Letters 5(4) (1986), 165-169, the recognition of single-peaked preferences
  2. Jean-Paul Doignon and Jean-Claude Falmagne, A polynomial time algorithm for unidimensional unfolding representations, Journal of Algorithms 16(2) (1994), 218-233, the direct algorithm that builds the axis
  3. Bruno Escoffier, Jérôme Lang and Meltem Öztürk, Single-peaked consistency and its complexity, Proceedings of ECAI 2008, 366-370, the direct algorithm for single-peaked consistency
  4. Edith Elkind, Martin Lackner and Dominik Peters, Preference restrictions in computational social choice: a survey, arXiv 2205.09092, version 2, March 2025, Section 4.1 (the consecutive ones reduction, Algorithm 1 and Theorem 4.2) and Section 4.8 (nearly single-peaked profiles, Table 2)

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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example