Why Pólya Enumeration Matters
A circular pattern has four positions, each colored red or blue. Rotations identify patterns, while reflections and exchanging the color names are not additional equivalences. There are six rotationally distinct patterns in total, but a designer may ask a more specific question: how many use exactly two red positions? The answer is two: red positions can be adjacent or opposite.
Burnside's lemma counts symmetry classes by averaging fixed configurations. Pólya enumeration retains the cycle lengths of each symmetry and uses generating functions to record color inventories. It can return a whole distribution instead of one total. The same idea supports catalogs of symmetric tiles, circular sequences, and substitution patterns on a fixed molecular skeleton, provided the allowed symmetries are modeled correctly.
This lesson develops the general theorem and then implements a focused case: the number of binary necklaces with each possible red-bead count, under rotations only. You will trace a cycle-index substitution, build its coefficients with dynamic programming, and compare independently runnable Python, C++, and Java programs. The polynomial recurrence connects directly to basic DP; the group action specifies which configurations count as the same object.
Pólya enumeration packages a finite permutation group's cycle structures into its cycle index. Substituting a color-weight sum for each cycle length produces a polynomial whose coefficients count symmetry classes with specified color inventories.
Core Concepts and Terminology
Let $G$ be a finite group permuting $n$ positions. It acts on colorings by moving positions while preserving color names. An orbit is one equivalence class of colorings under those transformations. For a permutation $g\in G$, let $m_\ell(g)$ be its number of cycles of length $\ell$, including cycles of length one. Every position belongs to exactly one cycle, so
$$ \sum_{\ell=1}^{n}\ell\,m_\ell(g)=n. $$
Introduce formal variables $a_1,\ldots,a_n$. The cycle index is
$$ Z_G(a_1,\ldots,a_n)=\frac{1}{\lvert G\rvert} \sum_{g\in G}\prod_{\ell=1}^{n}a_\ell^{m_\ell(g)}. $$
The subscript records cycle length; the exponent records how many such cycles occur. For rotations of four positions, the identity has four one-cycles, the half-turn has two two-cycles, and each quarter-turn has one four-cycle. Therefore
$$ Z_{C_4}=\frac{a_1^4+a_2^2+2a_4}{4}. $$
A coloring fixed by a permutation is constant on every cycle. If the available color weights are $w_1,\ldots,w_c$, a monochromatic cycle of length $\ell$ contributes one of $w_1^\ell,\ldots,w_c^\ell$. Pólya's inventory theorem makes the substitution
$$ a_\ell\longleftarrow\sum_{i=1}^{c}w_i^\ell. $$
This is the cycle-index and inventory framework described in Stanford's cycle-index notes and inventory theorem notes. Setting every color weight to one recovers the total orbit count; keeping variables distinguishes inventories.
For binary colorings, give red weight $z$ and blue weight $1$. A cycle contributes $1+z^\ell$, and the inventory polynomial is
$$ I_G(z)=Z_G(1+z,1+z^2,\ldots,1+z^n). $$
The coefficient $[z^q]I_G(z)$ counts orbits with exactly $q$ red positions. Although the cycle index has rational coefficients, the resulting inventory has nonnegative integer coefficients. Every coloring in an orbit has the same inventory, so the weight is well-defined for that orbit.
| Term | Definition | Four-position example |
|---|---|---|
| Acting group $G$ | Permutations declared equivalent | $C_4$ contains four rotations |
| Cycle type | Counts of cycles of each length | A half-turn has $m_2=2$ and all other counts zero |
| Cycle-index monomial | Product recording one permutation's cycle type | The half-turn contributes $a_2^2$ |
| Multiplicity | Number of group elements of a type | Two quarter-turns contribute $2a_4$ together |
| Color weight | A variable or value attached to a color | Red has weight $z$; blue has weight $1$ |
| Power-sum substitution | A monochromatic cycle's possible weights | A two-cycle contributes $1+z^2$ |
| Inventory coefficient | Number of orbits with a specified red count | $[z^2]I_{C_4}(z)=2$ |
| Modular output | Each inventory coefficient reduced modulo a prime | The programs return $n+1$ residues for red counts $0$ through $n$ |
How Pólya Enumeration Works, Step by Step
The general workflow is to choose the group, classify permutation cycles, substitute color weights, combine polynomials with multiplicities, and average over the group. We specialize this workflow to rotations of $n\ge1$ positions and two named colors, without any adjacency constraint.
A rotation by $r$ positions has $d=\gcd(n,r)$ cycles, all of length $L=n/d$. Its fixed-coloring polynomial is
$$ (1+z^L)^d=\sum_{j=0}^{d}\binom{d}{j}z^{jL}. $$
Selecting $j$ cycles to be red colors $jL$ positions red. Group rotations by $L$ and let $h_L$ be their multiplicity. Then
$$ I_{C_n}(z)=\frac1n\sum_L h_L(1+z^L)^{n/L}. $$
The code works modulo $p=1{,}000{,}000{,}007$, with $1\le n\lt p$. This makes $n$ invertible modulo $p$. It computes the numerator's coefficient array first and multiplies every entry by $n^{p-2}\bmod p$ afterward.
- Visit shifts $r=0,\ldots,n-1$. Compute $L=n/\gcd(n,r)$ and increment
types[L]. The multiplicities must sum to $n$. - Initialize the numerator array
totalwith $n+1$ zeros. - Process the distinct lengths $L$ in ascending order. Put $d=n/L$ and build the coefficients of $(1+t)^d$ in a compressed array
chooseof length $d+1$. - Begin with
choose[0] = 1. For each new cycle, update indices from the newly reachable highest index down to one usingchoose[j] += choose[j - 1], modulo $p$. - For every $j=0,\ldots,d$, add
types[L] * choose[j]modulo $p$ intototal[j * L]. Only multiples of $L$ can occur for this cycle type. - Multiply all entries of
totalby the modular inverse of $n$ and return the array.
The compressed variable $t$ tracks red cycles; expansion replaces $t$ by $z^L$, which tracks red positions. The descending sweep is essential here: each cycle is assigned a color exactly once. This is a zero-or-one choice per cycle, unlike a DP in which an item may be reused without limit.
flowchart TD
A["Read necklace length n"] --> B{"1 at most n and n less than p?"}
B -- No --> C["Reject input"]
B -- Yes --> D["Group every rotation by cycle length"]
D --> E["Initialize numerator array to zero"]
E --> F{"Another cycle length L?"}
F -- Yes --> G["Set d = n divided by L; initialize choose"]
G --> H{"Another cycle to include?"}
H -- Yes --> I["Update choose in descending order modulo p"]
I --> H
H -- No --> J["Add weighted coefficients at indices j times L"]
J --> F
F -- No --> K["Compute inverse of n modulo p"]
K --> M["Scale every coefficient and return inventory"]
Worked Example with a Full Trace
Use four positions, with red weight $z$ and blue weight $1$. Scan the rotations in order. Shift $0$ gives $L=1$, so the histogram becomes {1: 1}. Shift $1$ gives $L=4$, producing {1: 1, 4: 1}. Shift $2$ gives $L=2$, producing {1: 1, 4: 1, 2: 1}. Shift $3$ gives $L=4$ again, producing {1: 1, 4: 2, 2: 1}. The multiplicities sum to $4$.
Start the numerator at [0, 0, 0, 0, 0]. Each index is a red-position count.
For length $L=1$, there are $d=4$ cycles and multiplicity $1$. The compressed array begins [1, 0, 0, 0, 0]. Its four completed passes are [1, 1, 0, 0, 0], [1, 2, 1, 0, 0], [1, 3, 3, 1, 0], and [1, 4, 6, 4, 1]. For a complete inner-loop trace, the writes (index, new value) in these passes are $(1,1)$; then $(2,1),(1,2)$; then $(3,1),(2,3),(1,3)$; then $(4,1),(3,4),(2,6),(1,4)$. Every other entry retains its preceding value until its own write. Expansion changes no indices because $L=1$. The running numerator becomes [1, 4, 6, 4, 1].
For length $L=2$, there are $d=2$ cycles and multiplicity $1$. The compressed states are [1, 0, 0], [1, 1, 0], and [1, 2, 1]. The individual writes are $(1,1)$ in the first pass, then $(2,1),(1,2)$ in the second. Place these entries at red counts $0,2,4$, giving [1, 0, 2, 0, 1]. The running numerator becomes [2, 4, 8, 4, 2].
For length $L=4$, there is $d=1$ cycle and multiplicity $2$. The compressed states are [1, 0] and [1, 1]. Expansion gives [1, 0, 0, 0, 1], and the multiplicity doubles it to [2, 0, 0, 0, 2]. The final numerator is [4, 4, 8, 4, 4].
Dividing each coefficient by $4$ gives [1, 1, 2, 1, 1], or
$$ I_{C_4}(z)=\frac{(1+z)^4+(1+z^2)^2+2(1+z^4)}4 =1+z+2z^2+z^3+z^4. $$
The coefficient of $z^2$ is $2$: representatives are 0011 and 0101, with 1 denoting red. The coefficients sum to $I_{C_4}(1)=6$, agreeing with the total binary necklace count. Under the modulus, the program uses $4^{-1}\bmod p=250{,}000{,}002$; all these small results are also their exact counts.
Trace It by Hand
Pause after the length-one type, when the numerator is [1, 4, 6, 4, 1]. For the length-two type, the compressed coefficients are [1, 2, 1]. Predict where those entries belong and the new numerator before reading on.
A red cycle contains two positions, so compressed indices $0,1,2$ map to red-position counts $0,2,4$. Add [1, 0, 2, 0, 1], giving [2, 4, 8, 4, 2]. Next, the two quarter-turns add [2, 0, 0, 0, 2]. Averaging yields [1, 1, 2, 1, 1]. Explain why neither nonidentity cycle type can contribute to a coloring with exactly one red position.
Implementation in Python, C++, and Java
Each program returns the complete binary necklace inventory, modulo the same explicit prime. Entry $q$ counts rotational equivalence classes containing exactly $q$ red positions. Blue and red remain different named colors; exchanging them maps one inventory to its complementary inventory rather than identifying the two.
The input contract is $1\le n\lt p$, and the required arrays and computation must fit available resources. Length zero is rejected. This implementation constructs the rotation group's cycle types itself; it does not accept arbitrary groups or include reflections. The general cycle-index substitution above explains how to extend it.
All three programs print modulus = 1000000007 followed by I(1) = [1, 1], I(2) = [1, 1, 1], I(4) = [1, 1, 2, 1, 1], I(6) = [1, 1, 3, 4, 3, 1, 1], and I(8) = [1, 1, 4, 7, 10, 7, 4, 1, 1], one result per line. The notation I(n) in this output labels the coefficient array for length $n$.
Python uses exact integers, C++ uses long long, and Java uses BigInteger. C++ reduces each weighted product before adding it. Each product is at most $(p-1)^2=1{,}000{,}000{,}012{,}000{,}000{,}036$, safely below the signed $64$-bit limit, and each subsequent sum is at most $2p-2$. The programs never use floating-point division. In Java, save the complete panel as Main.java.
Complexity, Correctness, and Invariants
For this implementation, let $\tau(n)$ be the number of divisors of $n$. Rotation classification uses $n$ greatest-common-divisor computations and dictionary operations, taking $O(n\log(n+1))$ time under ordinary integer and map bounds. Every occurring cycle length divides $n$.
A type with $d$ cycles performs exactly $d(d+1)/2$ coefficient updates. Across all types, the dominant work is $\Theta(\sum_{d\mid n}d^2)$. This sum is at least $n^2$, because the identity contributes $d=n$, and at most
$$ n^2\sum_{L=1}^{\infty}\frac1{L^2}\lt2n^2. $$
Thus the DP work is $\Theta(n^2)$. The total bound is $O(n^2+\log p)$ time, including the inverse, and $\Theta(n)$ space for the output, temporary coefficients, and type map. With the fixed prime, the time is $\Theta(n^2)$. There is no configuration-dependent branching: for a fixed length, best, average, and worst cases have the same operation count. An average across different lengths would require a distribution. These are arithmetic-operation bounds for bounded modular values, not arbitrary-size integer bit bounds.
Correctness has two levels. A coloring fixed by a permutation assigns one color to each complete cycle, giving the substituted product. Averaging these fixed-coloring polynomials counts each orbit once because its weight is constant across the orbit: the weighted version of Burnside's double-counting proof applies coefficient by coefficient. For the implementation, the compressed recurrence produces the binomial coefficients, expansion maps red cycles to red positions, and multiplicities restore all group elements. Multiplication by the valid inverse performs the final averaging modulo $p$.
| Method | Time | Space | Assumptions and purpose |
|---|---|---|---|
| Grouped binary inventory DP shown here | $O(n^2+\log p)$ | $\Theta(n)$ | Rotations only; all red-count coefficients; $1\le n\lt p$ |
| Burnside total-count formula | $O(n\log(n+1)+\log p)$ | $O(1)$ modular values | Returns only the total number of binary necklaces |
| Enumerate and canonicalize binary strings | $O(2^n n^2)$ using every rotation explicitly | Up to $O(nN(n,2))$ stored representatives | Tiny exhaustive verifier; records actual orbit representatives |
| Explicit-permutation binary inventory DP | $O(hn^2)$ upper bound for $h$ group elements | $O(n)$ scratch, excluding group storage | Handles arbitrary supplied position-permutation groups |
| Grouped binomial rows with inverse-factorial tables | $O(n+\tau(n)\log(\tau(n)+1)+\sum_{d\mid n}d+\log p)$ after cycle types are known | $O(n)$ | Faster coefficient generation; uses prime-modulus inverses with $n\lt p$ |
After processing $b$ cycles of one type, choose[j] equals $\binom{b}{j}\bmod p$; descending updates preserve the previous pass's entries. After each cycle type, total[q] is the coefficient of $z^q$ in the fixed-coloring polynomials of all processed group elements, with multiplicities included; averaging these coefficients yields the required orbit inventories.
Variants, Pitfalls, and Optimizations
More colors and fixed inventories. Give three colors weights $x,y,z$. Replace $a_L$ by $x^L+y^L+z^L$ and extract $[x^r y^g z^b]$ for prescribed counts. A cycle of length $L$ contributes $L$ positions of one color, not one position. The polynomial dimension and coefficient storage can grow quickly; track only the counts needed, with one color often determined by the total.
Recover a scalar count. Set all inventory variables to one. With $c$ unrestricted colors, each cycle-index variable becomes $c$, yielding $Z_G(c,\ldots,c)$. For the binary program, summing the returned coefficients modulo $p$ recovers the binary necklace total. Retaining only that total would discard the inventory information this lesson computes.
Choose the correct group. Include reflections to count bracelets; include other position permutations only when the application declares them equivalent. Four rotations form $C_4$, while a square's rotations and reflections form $D_4$ with eight elements. Renaming colors is another equivalence and is not automatically included by the ordinary position-action substitution. For constrained colorings such as proper graph colorings, plain independent cycle choices may fail; the constraints must be preserved and counted within each fixed set.
Build cyclic types directly. The cycle index of the rotation group also has the divisor form
$$ Z_{C_n}=\frac1n\sum_{L\mid n}\varphi(L)a_L^{n/L}, $$
where $\varphi$ is Euler's totient function. Thus $h_L=\varphi(L)$. Factoring $n$ and generating its divisors can replace the scan of all shifts. Include those preparation costs when comparing implementations.
Generate binomial coefficients faster. The teaching code builds each row by additions to expose the DP invariant. Since $n\lt p$, factorial and inverse-factorial tables can generate $\binom{d}{j}\bmod p$ in constant time per entry after preprocessing. A multiplicative recurrence with valid modular inverses is another option. Neither approach permits ordinary integer division of already-reduced residues.
Keep cycle lengths in the substitution. The tempting replacement $a_2\leftarrow1+z$ counts red two-cycles rather than red positions. The correct replacement is $1+z^2$. Applied to the half-turn, the incorrect product $(1+z)^2$ invents a contribution at red count one; no half-turn-invariant coloring can have only one red position.
Preserve descending updates and multiplicities. An ascending compressed sweep can reuse a cycle within one pass, producing coefficients that no longer equal the binomial row. Dropping the second quarter-turn also corrupts the numerator. Finally, if the group order is not invertible under the chosen modulus, divide exact integer coefficients before reducing, or use an appropriate larger-modulus method; this code rejects lengths outside its stated invertible range.
A cycle of length $L$ contributes $1+z^L$, not $1+z$: inventory exponents count positions. Keep every cycle type's multiplicity, update the compressed DP downward, and verify that the group order is invertible before modular averaging.
Practice Problems and Real-World Use
Start each problem by specifying what is permuted, which transformations are allowed, and what the variables measure. Compute the cycle index or enough of its terms to extract the target coefficient. The small targets below can be verified by canonicalizing all allowed colorings under the stated symmetries.
| Exercise or application | Inventory question or check | Difficulty |
|---|---|---|
| Binary circular design catalog | Four positions, rotations only, exactly two red: $[z^2]I_{C_4}=2$ | Easy |
| Exhaustive test-data inventory | Six binary positions, rotations only: coefficients $[1,1,3,4,3,1,1]$ sum to $14$ | Medium |
| Ternary circular motifs | Three positions, rotations only, one of each color: $\left[xyz\right]\frac{(x+y+z)^3+2(x^3+y^3+z^3)}{3}=2$ | Medium |
| Square corner-tile catalog | Four binary corners with rotations and reflections, exactly two red: $2$ tile types | Medium |
| Circular sequence with a fixed composition | Eight binary positions, rotations only, four red: coefficient $10$ | Medium |
| Substitutions on a fixed symmetric skeleton | Four equivalent sites under all site permutations $S_4$, two substituent types, exactly two of each: $1$ orbit | Hard |
| Implement an independent inventory verifier | Enumerate short binary strings, canonicalize rotations, and tally representatives by red count | Medium |
For an additional check, exchange red and blue. This gives a bijection between inventories with $q$ and $n-q$ red positions, so every returned array must be symmetric. Its two endpoint coefficients must both be $1$, its entries must sum to the total necklace count modulo $p$, and the exhaustive verifier must agree coefficient by coefficient for short lengths.