# How does one compute the sign of a permutation?

The sign of a permutation $\sigma\in \mathfrak{S}_n$, written ${\rm sgn}(\sigma)$, is defined to be +1 if the permutation is even and -1 if it is odd, and is given by the formula

$${\rm sgn}(\sigma) = (-1)^m$$

where $m$ is the number of transpositions in the permutation when written as a product of transpositions.

Alternatively the sign is -1 if, when we express $\sigma$ as a product of disjoint cycles, the result contains an odd number of even-length cycles. Otherwise the sign is +1.

My permutations are expressed as tuples $(\sigma_1,\dots,\sigma_n)$, so neither the expression of the tuple as a product of disjoint cycles nor as a product of transpositions are immediately available to me.

This suggests two high-algorithms to compute the sign of a permutation:

1. Express the permutation as a product of transpositions and count the number of transpositions.

2. Express the permutation as a product of disjoint cycles and count the number of even-length cycles.

What are typical algorithms for accomplishing these tasks, and how do they vary in running type depending on $n$? Are there more efficient algorithms for calculating the sign of a permutation?

The motivation is to quickly decide whether instances of the fifteen puzzle are solvable. I want to generate a large number of solvable instances of the fifteen puzzle for testing some search algorithms. At the moment I generate a random instance, and test whether it is solvable by trying to solve it with depth-first search, which is fairly slow going, and won't generalize well to larger puzzles (24 puzzle, 35 puzzle...) due to time and memory limitations. Since solvable instances of the fifteen puzzle are in 1-1 correspondence with even elements of $\mathfrak{S}_{16}$, I figure that there must be a faster way of generating solvable instances.

It has just occurred to me that a better way of generating solvable instances of the puzzle might be to generate an even number of transpositions and multiply them together to generate an even permutation. I'd prefer an algorithm that was guaranteed to return an even distribution over $\mathfrak{S}_n$ though, and in fact I'm now sufficiently interested in the answer to this question in its own right.

• The parity of a permutation is also the number of inversions in the permutation modulo $2$. Since the number of inversions can be computed in $O(n \log n)$ time, parity can certainly be. It's an interesting question if even faster algorithms are possible. Off the top of my head, I can't think of any reason why $O(n)$ algorithm is impossible. (This is the best reference I could pull off right now for finding inversions: stackoverflow.com/questions/6523712/… .) – Srivatsan Sep 19 '11 at 23:58
• It seems the situation is more complicated. PengOne's answer in the other question says that there is a long-standing $O(n \frac{\log n}{\log \log n})$ algorithm and a recent $O(n \sqrt{\log n})$ algorithm for counting inversions. Actually, I think this question would be a good fit for cstheory.SE as well. – Srivatsan Sep 20 '11 at 0:02
• I think you can find this in Knuth. (No, I don't know where. It just feels like it's in there somewhere.) – Michael Lugo Sep 20 '11 at 0:16
• You should probably specify what encoding of a permutation you're using (in cycle notation, shouldn't you be able to compute the parity in $O(n)$ time?). – Qiaochu Yuan Sep 20 '11 at 0:27
• – lhf Sep 20 '11 at 0:52

So you have a permutation $f: X \to X$ for which you can efficiently compute $f(x)$ from $x$.

I think a good way to do any of the things you mentioned is to make a checklist for the elements of $X$. Then you can start with the first unchecked element and follow the chain $x, f(x), f(f(x))$, etc. checking off each element as you find it until you reach an element that is already checked. You have now traversed one cycle. Then you can pick the next unchecked element and traverse that cycle, and so on until all elements are checked.

While you traverse a cycle you can easily

1. Count the cycle length
2. Record the cycle, or
3. Record transpositions

All this works in roughly linear time. Obviously just counting the cycle lengths is going to be the fastest.

• Nice :). I totally missed that the cycle representation can indeed be obtained in linear time... – Srivatsan Sep 20 '11 at 1:05
• Thanks for your answer Niels. – Chris Taylor Sep 23 '11 at 14:11

It's worth mentioning the quadratic time algorithm, since it can be faster for small permutations:

$$\textrm{sgn}(\sigma) = (-1)^{\sum_{0 \le i<j<n} (\sigma_i>\sigma_j)}$$

I.e., the sign is negative iff there are an odd number of misordered pairs of indices. This algorithm also works if we're interested in the permutation defined by an unsorted list of integers where the cycle structure can't be determined in linear time.

• Wouldn't you need a sum over all $1 \leq i < j \leq n$? – Lynn Oct 13 '15 at 15:02
• Mauris: Fixed. I had left off the $0 \le$. – Geoffrey Irving Oct 13 '15 at 23:02

If $c_e(n)$ is the number of even-length cycles in a permutation $p$ of length $n$, then one of the formulas for the sign of a permutation $p$ is $\text{sgn}(p) = (-1)^{c_e(n)}$.

Here is an $O(n)$ Matlab function that computes the sign of a permutation vector $p(1:n)$ by traversing each cycle of $p$ and (implicitly) counting the number of even-length cycles. The number of cycles in a random permutation of length $n$ is $O(H_n)$, where $H_n$ is the $n$-th Harmonic Number.

function sgn = SignPerm(p);
% ----------------------------------------------------------
% Calculates the sign of a permutation p.
% p is a row vector p(1,n), which represents the permutation.
% sgn(p) = (-1)^(No. of even-length cycles)
% Complexity : O(n + ncyc) ~ O(n + Hn) ~~ O(n+log(n)) steps.
%
% Derek O'Connor 20 March 2011.
% ----------------------------------------------------------
n   = length(p);
visited(1:n) = false;                  % Logical vector which marks all p(k)
% not visited.
sgn = 1;
for k = 1:n
if ~visited(k)                     % k not visited, start of new cycle
next = k;
L = 0;
while ~visited(next)           % Traverse the current cycle k
L = L+1;                   % and find its length L
visited(next) =  true;
next    = p(next);
end
if rem(L,2) == 0               % If L is even, change sign.
sgn = -sgn;
end
end % if ~visited(k)
end % for k

• Every cycle of length $n$ can be factored into a product of $n-1$ transpositions (on the same elements). For example, $(abc\cdots)=(ab)(ac)\cdots$. This explains the $c_{\epsilon}(n)$ formula, since disjoint cycles factor into disjoint transpositions. – bgins Dec 15 '11 at 21:34

The inverse permutation can be constructed as a sequence of $n-1$ transpositions via Gaussian Elimination with partial pivoting, $P A = L U$, where $A$ is the original permutation matrix, $P=A^{-1}$, and $L=U=I$. Since the signature of the inverse permutation is the same as that of the original permutation, this procedure yields the sign of the permutation.

Thankfully, this algorithm can be run in linear time by maintaining the permutation and its inverse throughout a short-circuited Gaussian Elimination procedure since it can easily be seen that the Schur complement updates will always be zero.

$sgn(\sigma)=\prod_{i<j}\frac{\sigma(i)-\sigma(j)}{i-j}$ is quadratic, but straightforward to code.

Use the Fisher-Yates-Shuffle in its inside-out version to generate a permutation of the numbers $1\dots16$. You can find the parity of this permutation by counting the number of transpositions you performed. This is easy: Every time $i\neq j$ you perform a transposition. If the puzzle invariant is violated now, simply exchange two arbitrary tiles (not the empty spot) to make the puzzle solvable.

Here is the inside-out Fisher-Yates shuffle in a version that generates a random permutation in an array $a[1\dots n]$:

1. for $i$ from $1$ to $n$ do:
2. $j\leftarrow\mathop{\rm rnd}\{1\ldots i\}$
3. if $i\neq j$ then $a[i]\leftarrow a[j]$
4. $a[j]\leftarrow i$

Every time the branch in step 3 is taken, you perform a transposition and need to toggle your parity.

• I almost didn't see how this answered the question, because this question is an example of an "XY" problem. The OP really wanted to generate solvable puzzles (problem X), and guessed that a good way to do this was to shuffle the tiles (using a "black box" algorithm where the number of transpositions was not visible to the user) and then discard the shuffles that weren't solvable (problem Y). Instead of asking how to solve X, OP asked how to solve Y. You have offered a replacement for the black box that makes it possible to solve X without dealing with Y. – David K Sep 5 '17 at 22:56