6
Information Processing Letters 86 (2003) 107–112 www.elsevier.com/locate/ipl A CAT algorithm for generating permutations with a fixed number of inversions Scott Effler, Frank Ruskey ,1 Department of Computer Science, University of Victoria, Canada Received 18 December 2001; received in revised form 1 May 2002 Communicated by S.E. Hambrusch Abstract We develop a constant amortized time (CAT) algorithm for generating permutations with a given number of inversions. We also develop an algorithm for the generation of permutations with given index. 2003 Elsevier Science B.V. All rights reserved. Keywords: Permutation; Exhaustive listing; Inversion; Index; Algorithms 1. Introduction Among all statistics of permutations, the num- ber of inversions are of paramount importance to computer scientists because of their connection with sorting and searching algorithms. Furthermore, they have interesting combinatorial properties and are in- tensely studied in the mathematical literature (e.g., Margolis [7], Clark [3]). Both the computational and mathematical properties of permutations with a given number of inversions are nicely summarized by Knuth [4]. However, we know of no published algorithms for generating all n-permutations with a given number of inversions (or with given index). There are many * Corresponding author. E-mail addresses: [email protected] (S. Effler), [email protected] (F. Ruskey). 1 Research supported in part by NSERC grant OGP0003379. published algorithms for generating various types of permutations and many of these run in constant time per permutation, in an amortized sense. For example, there are algorithms for derangements [1], involutions [10], up-down permutations [2], and linear extensions of posets [9,5]. An algorithm runs in constant amortized time (CAT) if the amount of computation, after a small amount of preprocessing, is proportional to the num- ber of objects that are generated [8]. An inversion of a permutation π is a pair i j ) where i<j and π i j [4]. Let I(π) denote the number of inversions in π . Clearly, 0 I(π) ( n 2 ) , with the extremes occurring for 12 ··· n and n ··· 21. Following Knuth [4] we use I n (k) to denote the number of permutations of [n] with k inversions. By [n] we denote the set {1, 2,...,n}. This paper presents a CAT algorithm for generating permutations of [n] with a given number of inversions. The algorithm is outlined in Section 2. 0020-0190/03/$ – see front matter 2003 Elsevier Science B.V. All rights reserved. doi:10.1016/S0020-0190(02)00481-7

A CAT algorithm for generating permutations with a fixed number of inversions

Embed Size (px)

Citation preview

Information Processing Letters 86 (2003) 107–112

www.elsevier.com/locate/ipl

A CAT algorithm for generating permutationswith a fixed number of inversions

Scott Effler, Frank Ruskey∗,1

Department of Computer Science, University of Victoria, Canada

Received 18 December 2001; received in revised form 1 May 2002

Communicated by S.E. Hambrusch

Abstract

We develop a constant amortized time (CAT) algorithm for generating permutations with a given number of inversions. Wealso develop an algorithm for the generation of permutations with given index. 2003 Elsevier Science B.V. All rights reserved.

Keywords: Permutation; Exhaustive listing; Inversion; Index; Algorithms

1. Introduction

Among all statistics of permutations, the num-ber of inversions are of paramount importance tocomputer scientists because of their connection withsorting and searching algorithms. Furthermore, theyhave interesting combinatorial properties and are in-tensely studied in the mathematical literature (e.g.,Margolis [7], Clark [3]). Both the computationaland mathematical properties of permutations with agiven number of inversions are nicely summarized byKnuth [4].

However, we know of no published algorithms forgenerating alln-permutations with a given numberof inversions (or with given index). There are many

* Corresponding author.E-mail addresses: [email protected] (S. Effler),

[email protected] (F. Ruskey).1 Research supported in part by NSERC grant OGP0003379.

published algorithms for generating various types ofpermutations and many of these run in constant timeper permutation, in an amortized sense. For example,there are algorithms for derangements [1], involutions[10], up-down permutations [2], and linear extensionsof posets [9,5].

An algorithm runs in constant amortized time(CAT) if the amount of computation, after a smallamount of preprocessing, is proportional to the num-ber of objects that are generated [8].

An inversion of a permutationπ is a pair(πi,πj )

where i < j and πi > πj [4]. Let I (π) denote thenumber of inversions inπ . Clearly, 0� I (π) �

(n2

),

with the extremes occurring for 12· · ·n andn · · ·21.Following Knuth [4] we useIn(k) to denote thenumber of permutations of[n] with k inversions. By[n] we denote the set{1,2, . . . , n}. This paper presentsa CAT algorithm for generating permutations of[n]with a given number of inversions. The algorithm isoutlined in Section 2.

0020-0190/03/$ – see front matter 2003 Elsevier Science B.V. All rights reserved.doi:10.1016/S0020-0190(02)00481-7

108 S. Effler, F. Ruskey / Information Processing Letters 86 (2003) 107–112

The number of permutations of[n] with k inver-sions is equal to the number of restricted composi-tionsν1 + ν2 + · · · + νn = k where 0� νi < i. Such acomposition can be interpreted as an inversion vectorof a permutation. Thus any algorithm for generatingbounded compositions can also be used to generate theinversion vectors of permutations with a given numberof inversions.

Theindex of a permutationπ is the sum of indicesjsuch thatπj > πj+1, denotedJ (π) [4]. A theorem ofMacMahon [8] establishes a bijection between classesof permutations counted by the two statistics.

Theorem 1.1. The number of permutations of [n] withk inversions is the same as the number of permutationsof [n] with index k; i.e., both sets have cardinalityIn(k).

Even though there is a bijection between twosets, a fast algorithm for generating one set will notnecessarily imply the existence of a fast algorithm forgenerating the other set. An algorithm for generatingpermutations with fixed indexk that appears to be CATin the range 2< k <

(n2

) − 2 is given in Section 3.

2. Generating permutations with a given numberof inversions

In this section, we develop a CAT algorithm forgenerating all permutationsπ ∈ Sn where I (π) isequal to some given valuek.

2.1. Algorithm

The algorithm works from right to left in the oneline notation of the permutation by placing elementsone at a time. The key to the algorithm is the followinglemma.

Lemma 2.1. Given natural numbers n, k with 0 � k �(n2

), and x ∈ [n], there is a permutation π ∈ Sn of the

form π = π1π2 · · ·πn−1x such that I (π) = k if andonly if

n − x � k �(

n − 1

2

)+ n − x. (1)

Proof. We must show both directions of the lemma.(⇒) Supposeπ = π1 · · ·πn−1x andI (π) = k. The

number of inversions inπ1 · · ·πn−1 satisfies

0 � I (π1 · · ·πn−1) �(

n − 1

2

).

There are exactlyn − x inversions of the form(πi, x).Thus, we have

n − x � I (π) �(

n − 1

2

)+ n − x.

(⇐) Suppose the inequality in the lemma is satis-fied for n, k, andx. There is a permutationπ1π2 · · ·πn−1 of [n] \ {x} such thatI (π1π2 · · ·πn−1) = k −n + x since 0� k − n + x �

(n−1

2

)by (1). But then

π1π2 · · ·πn−1x ∈ Sn andI (π1π2 · · ·πn−1x) = k. ✷We only recurs if it is possible to extend the partial

permutation to a permutation with the given number ofinversions. That is to say, no branch in the computationtree is a dead-end. Such algorithms are said [8] to beBEST (backtracking ensuring success at terminals).BEST algorithms are often fast in practice and aregenerally easier to analyze.

Our algorithm generates permutations of[N]. De-fine rank(x) as the position ofx in the ordered listX = [N] \ {πn+1, . . . , πN } of remaining elements. No-tice that then − rank(x) is the number of inversionscreated by placing elementx at the current position,n. The method is outlined in Fig. 1.

Lemma 2.2. Given that πn+1 · · ·πN is an (N − n)-permutation of {1,2, . . . ,N}, the call gen(n, k) gen-erates all permutations π1π2 · · ·πN of {1,2, . . . ,N}such that I (π1 · · ·πn) = k.

Proof. Our proof is by induction onn. Since theempty permutation has no involutions, the lemma istrue whenn = 0.

gen(n, k)

(1) if n = 0∧ k = 0 then outputπ1π2 · · ·πN

(2) for each x ∈ [N] \ {πn+1, . . . , πN }(a) if n− rank(x) � k �

(n−12

) + n − rank(x) then(i) πn := x

(ii) gen(n − 1, k − n + rank(x))

Fig. 1. Generating permutations with given number of inversions.

S. Effler, F. Ruskey / Information Processing Letters 86 (2003) 107–112 109

There are preciselyn − rank(πn) inversions of theform (πi,πn). By Lemma 2.1 we know thatπn can beany value such that

n − rank(x) � k �(

n − 1

2

)+ n − rank(x).

Inductively, for each possible value ofx = πn, therecursive call gen(n − 1, k − n + rank(πn)) generatesall permutations for whichI (π1 · · ·πn−1) = k − n +rank(πn). Together with then − rank(πn) inversionscreated by elementπn, we have generated alln-per-mutations withk inversions. ✷Corollary 2.1. The call gen(N,K) generates allpermutations π1π2 · · ·πN of {1,2, . . . ,N} such thatI (π1π2 · · ·πn) = K .

The following result is important in determining theorder to traverse the listX of remaining elements ofthe permutation.

Lemma 2.3. If a1 < a2 < · · · < an where {a1, a2, . . . ,

an} = [N] \ {πn+1, . . . , πN } then those ai that satisfythe condition in Lemma 2.1 form a contiguous subse-quence ai, ai+1, . . . , aj where i = 1 or j = n.

Proof. It is clear from (1) that the values occur ina contiguous subsequence. We will show, under theassumption that 0� k �

(n2

), that (1) is satisfied for

x = 1 or x = n (or both), which will suffice to provethe lemma.

So suppose that (1) fails forx = n. Then eitherk < 0 or k >

(n−1

2

). Since the former cannot occur we

have(n − 1

2

)< k �

(n

2

).

Hence

n − 1 �(

n − 1

2

)< k �

(n

2

)=

(n − 1

2

)+ n − 1,

which is (1) whenx = 1. ✷If 0 < k �

(n−1

2

)then we traverse the list in

reverse order from the largest to the smallest element.Otherwise, we traverse the list in order from thesmallest to the largest element. In either case, if thetest in step 2(a) of the algorithm of Fig. 1 fails, westop traversing the list. Implemented in this way, thealgorithm has the crucial property that its running timeis proportional to the total number of nodes in itscomputation tree. In order to maintain the list we usethe technique dubbed “dancing links” by Knuth [6].

2.2. Example

As an example, consider generating all permuta-tions of length 4 with 2 inversions. The five suchpermutations are{3124,2314,2143,1423,1342}. Thecomputation tree is given in Fig. 2. The list of re-maining permutation elements at each node is given

Fig. 2. Example of the algorithm of Fig. 1.

110 S. Effler, F. Ruskey / Information Processing Letters 86 (2003) 107–112

in square brackets followed by the current values ofn

andk, along with the current partial permutation.Consider the leftmost child of the root as an

example. We already know that any child permutationends in a 4 and has two inversions to the left of thecurrent position. The next step is to find a value forthe third position. This position cannot be 3 sincethis leaves only 1 and 2, which can only produceone inversion. Therefore, this node has two children,as shown in the computation tree. This process iscontinued recursively until all positions are filled in.

2.3. Path elimination

We notice that there may be many successive nodesin the computation tree with only one child. Thisleads to inefficiency since, for example, to generatethe one permutation withk = 0 takes time�(n), andto generate then − 1 permutations withk = 1 takestime �(n2). To combat this problem, we will apply apath elimination technique (PET) from [8] and stop therecursion early. This will allow us to eliminate most,but not all of the nodes in the recursive computationtree that have one child. Details of this processfollow.

First, if k = 0, there is always just one validpermutation ofX; the one with all elements ascending.We do not eliminate such paths, unless they arisefrom a k = 1 node higher in the tree. Ifk = 1, wecan easily generate all valid permutations ofX inconstant amortized time by starting with all elementsin ascending order and swapping one pair of adjacentelements at each step. For example, ifn = 4 andX = [4], the permutations are{2134,1324,1243}. So,if k = 1, we stop the recursion and generate then − 1permutations directly in time�(n).

Similarly, if k = (n2

), then there is exactly one valid

permutation; the the one with all elements descending.To eliminate many of these 1-paths we notice thatif k = (

n2

) − 1 we can easily generate all validpermutations in constant amortized time by startingwith all elements in descending order and swappingone pair of adjacent elements at each step. So, ifk =(n2

) − 1 we again stop the recursion and generate then − 1 permutations directly in time�(n).

In Fig. 2 the two nodes with darker borders are theroots of subtrees withk = 1 andk = (

n2

)(with n = 3).

The subtrees at these nodes are replaced with non-

recursive calls. One 1-path remains and it is indicatedby the nodes with the black dots in their lower rightcorners. The cost of computing this path is assigned tothe subtree rooted at the highlightedk = 1 node.

Now, we state and prove the main theorem ofthis paper. The argument that our algorithm runs inconstant amortized time is dependent upon the listtraversal and path elimination techniques discussedearlier.

Theorem 2.1. The algorithm of Fig. 1 with pathelimination techniques generates permutations with agiven number of inversions in constant amortized time.

Proof. By our earlier discussion the computation timeof the algorithm is proportional to the number of nodesin its recursive computation tree. If call withk = 1 ork = (

n2

) − 1 occurs, then then − 1 permutations aregenerated in�(n) time by a separate non-recursiveroutine and we regard the corresponding subtreesas being replaced by a single node in the recursivecomputation tree. Now every root of a 1-path in thecomputation tree hask = 0 or k = (

n2

). A root r of

a 1-path withk = 0 can occur only once amongst itssiblings, and it must have a siblingq with k = 1. The�(n) cost of generating the one path is charged to then − 1 leaves of the subtree represented byq . A rootof a 1-path withk = (

n2

)is handled in an analogous

manner. A subtree can only be charged once by thisscheme (unlessn = 3 in which case it can be chargedtwice). If 1 < k <

(n2

) − 1, then an internal node ofthe computation tree has at least two children. Thusthe total number of such internal nodes is less than thenumber of leaves. ✷

3. Generating permutations with given index

In this section, we are concerned with the genera-tion of all π such thatJ (π) is equal to some givenvalue. The algorithm for this problem has a similarflavor to the algorithm of Fig. 1 for generating per-mutations with a given number of inversions, but thereare significant and subtle differences. For fixedk in therange 2< k <

(n2

)−2 the algorithm appears to be CATin the sense that the amortized time per permutation isobserved to be decreasing for large enoughn.

S. Effler, F. Ruskey / Information Processing Letters 86 (2003) 107–112 111

3.1. Algorithm

As was the case for inversions, this algorithm worksfrom right to left. We assume that we are generatingpermutations of[N]. In order to treat all positionsin a uniform manner we will assume thatπN+1 =N + 1. Some simple results will help us constructan algorithm in much the same way as was done forinversions.

Consider a permutation of[n] of the formπ1π2 · · ·πn−1x. For x fixed in positionn, the permutation ofsmallest index is

(x+1)(x+2) · · ·(x + (n−x))12· · ·(x − 1)x

and the permutation of greatest index is

(x−1) · · ·21(x+(n−x)

) · · · (x+2)(x+1)x.

The index of those permutations isn − x and(n2

) −x + 1, respectively. Based on this observation andreasoning similar to that used to prove Lemma 1, weare led to the following lemma.

Lemma 3.1. Given a triple (n, x, k) of integers, thereis a permutation π of the form π = π1 · · ·πn−1x suchthat J (π) = k if and only if

n − x � k �(

n

2

)− x + 1. (2)

The algorithm of Fig. 3 generates alln-permuta-tions with indexk. It is based on Lemma 3.1, exceptthat we need to userank(x) instead ofx and if x >

πn+1 then the index target needs to be adjusted byn.

Lemma 3.2. Given that πn+1 · · ·πN is an (N − n)-permutation of {1,2, . . . ,N}, the call gen(n, k) willgenerate all permutations π1π2 · · ·πN of {1,2, . . . ,N}such that J (π1 · · ·πn) = k.

gen(n, k)

(1) if n = 0∧ k = 0 then outputπ1π2 · · ·πN

(2) for each x ∈ [N] \ {πn+1, . . . , πN }(a) πn := x;(b) if x > πn+1 then k′ := k − n; else k′ := k;(c) if n − rank(x) � k′ �

(n2) − rank(x) + 1

(i) then gen(n − 1, k′)

Fig. 3. Generating permutations with given index (assumesπN+1 = N + 1).

Proof. We will prove this result by induction onn.Since the empty permutation has index 0. The lemmais true whenn = 0.

If n = N or πn < πn+1 thenπn does not contributeto the index. By Lemma 3.1 we know thatπn can beany value such that

n − rank(x) � k �(

n

2

)− rank(x) + 1.

For each possible value ofx = πn, we recurs with callgen(n − 1, k). By our inductive assumption this callgenerates all permutations such thatJ (π1 · · ·πn−1) =k.

If πn > πn+1 thenπn contributesn to the index. ByLemma 3.1 we know thatπn can be any value suchthat

n − rank(x) � k − n �(

n

2

)− rank(x) + 1.

For each possible value ofx = πn, we recurs withcall gen(n − 1, k − n). By our inductive assump-tion this call generates all permutations such thatJ (π1 · · ·πn−1) = k − n. Together with then added tothe index byπn, we have generated alln-permutationswith indexk. ✷Corollary 3.1. The call gen(N,K) will generate allpermutations π1π2 · · ·πN of {1,2, . . . ,N} such thatJ (π1 · · ·πn) = K .

A similar result to Lemma 2.3 is necessary todetermine which order to traverse the list of remainingpermutation elements.

Lemma 3.3. If a1 < · · · < ap−1 < πn+1 < ap < · · · <an where {a1, a2, . . . , an} = [N] \ {πn+1, . . . , πN },then

• for 1 � i < p, those ai that satisfy the conditionin Lemma 3.1 for (n, ai, k) form a contiguoussubsequence ai, ai+1, . . . , aj where i = 1 or j =p − 1, and

• for p � i < n, those ai that satisfy the conditionin Lemma 3.1 for (n, ai, k − n) form a contigu-ous subsequence ai, ai+1, . . . , aj where i = p orj = n.

Proof. It is clear from (2) that the values occur in acontiguous subsequence.

112 S. Effler, F. Ruskey / Information Processing Letters 86 (2003) 107–112

For 1� i < p, we will show that if (2) is satis-fied for ai then it is satisfied forai+1, . . . , ap−1 ora1, . . . , ai−1 (or both), which will suffice to prove thefirst half of the lemma. If (2) is satisfied forai then wehave

n − rank(ai) � k �(

n

2

)− rank(ai) + 1.

If n − rank(ai) �= k thenx = rank(aj ) satisfies (2) for1 � j < i. If

(n2

)− rank(ai)+1 �= k thenx = rank(aj )

satisfies (2) fori < j < p.Forp � i � n, the argument is identical exceptk is

replaced byk − n. ✷At each step of the algorithm, we will traverse the

list four times. Once from largest to smallest, oncefrom smallest to largest and in both directions startingfrom the element with rankp−1 whererank(πn+1) =p. In all of these cases, if the test of step 2(c) ofthe algorithm of Fig. 3 fails, we stop traversing thelist. Also note that we must keep track of where eachtraversal ends, making sure that we do not recurs onthe same element twice. Implemented in this way, thealgorithm has the crucial property that its running timeis proportional to the total number of nodes in itscomputation tree.

Similar improvements can be made to this algo-rithm as were made to the inversion generation algo-rithm so as to produce a constant amortized time algo-rithm, but only if 2< k <

(n2

) − 2, and this has onlybeen observed experimentally.

Let {a1, a2, . . . , an} = [N] \ {πn+1, . . . , πN } wherea1 < a2 < · · · < an. If k = 0 andan < πn+1 then thereis only one valid permutation; the one with all ele-ments ascending. We do not eliminate such paths, un-less they arise from ak = 1 node, wherean < πn+1,higher in the computation tree. Ifk = 1 and an <

πn+1, we can easily generate all valid permutationsin constant amortized time by starting with the iden-tity and doing swaps(π1,π2), (π1,π3), . . . , (π1,πn),printing each intermediate permutation.

Similarly, if k = (n2

)and an < πn+1, then there

is exactly one valid permutation; the one with allelements descending. To eliminate many of these1-paths we notice that ifk = (

n2

) − 1 and an <

πn+1 we can easily generate all valid permutations inconstant amortized time by starting with all elements

in descending order and swapping as done above fork = 1.

4. Final remarks

The algorithms described in this paper are usedin the second author’s “Combinatorial Object Server”at http://www.theory.csc.uvic.ca/˜cos/ in the permuta-tions section. Java implementations of the algorithmscan also be downloaded there.

Note added in proof. We recently learned of TimWalsh’s algorithm [11] for generating permutationswith a given number of inversions. His algorithmhas the remarkable properties (a) that successivepermutations differ by the product of two adjacenttranspositions and (b) it can be implemented so as tobe loop free. Our algorithm has the advantage of beingfar simpler to describe and implement.

References

[1] S.G. Akl, A new algorithm for generating derangements,BIT 20 (1980) 2–7.

[2] B. Bauslaugh, F. Ruskey, Generating alternating permutationslexicographically, BIT 30 (1990) 17–26.

[3] L.A. Clark, An asymptotic expansion for the number ofpermutations with a certain number of inversions, Electron. J.Combin. 7 (2000) #R50.

[4] D.E. Knuth, The Art of Computer Programming, Vol. 3:Sorting and Searching, 2nd edn., Addison-Wesley, Reading,MA, 1998.

[5] D.E. Knuth, The Art of Computer Programming, Vol. 4:Prefascicle 2B, January 2002.

[6] D.E. Knuth, Dancing links, in: Millennial Perspectives in Com-puter Science, Palgrave, Houndmills, Basingstoke, Hampshire,2000, pp. 187–214.

[7] B.H. Margolis, Permutations with inversions, J. Integer Seq. 4(2001), Article 01.2.4.

[8] F. Ruskey, Combinatorial generation, Working version of bookin progress, 1995–2002.

[9] G. Pruesse, F. Ruskey, Generating linear extensions fast, SIAMJ. Comput. 23 (1994) 373–386.

[10] D. Roelants van Baronaigien, Constant time generation of in-volutions, in: Proceedings of the 23rd Southeastern Interna-tional Conference on Combinatorics, Graph Theory, and Com-puting (Boca Raton, FL, 1992), in: Congr. Numer., Vol. 90,1992, pp. 87–96.

[11] T. Walsh, Loop-free sequencing of bounded integer composi-tions, J. Combin. Math. Combin. Comput. 33 (2000) 323–345.