liveBook · Manning

Next lexicographic permutation algorithm

As explained in Fabulous Adventures in Data Structures and Algorithms

Pandita's algorithm is an in-place algorithm that transforms a permutation into its next lexicographically ordered permutation when one exists.

The next lexicographic permutation algorithm, also called Pandita’s algorithm, mutates a permutation in place to produce the immediately following dictionary-ordered arrangement. It supports duplicate elements and returns false when the input is already in reverse order, so no larger permutation exists. section 6.2.1

For a mutable sequence, the transformation proceeds as follows:

  • Scan from the right to find the first element smaller than the element immediately to its right. section 6.2.1
  • If no such element exists, the sequence is reverse-ordered; return false. section 6.2.1
  • Find the rightmost element larger than the pivot, swap the two, and reverse the suffix after the pivot. section 6.2.1
  • To enumerate every permutation, begin with the sequence in alphabetical order and repeatedly call NextLexiPermutation until it returns false. section 6.2.1

From COATS to COSAT

In COATS, A is the rightmost element immediately followed by something larger. S is the rightmost element larger than A. Swapping them produces COSTA; reversing the suffix TA produces COSAT, the next permutation. Continuing yields COSTA, COTAS, COTSA, and later arrangements. section 6.2.1

How Fabulous Adventures in Data Structures and Algorithms covers it

How deep it goes
Works through pivot selection, successor selection, swapping, suffix reversal, termination, and C# helper methods.
Examples
Uses COATS, COSAT, repeated character permutations of ABBEY, and a C# enumeration loop.
What it assumes
Assumes mutable sequences and element comparison, while defining lexicographic ordering through dictionary-style examples.
What you can do after
Apply it via NextLexiPermutation to enumerate duplicate-containing permutations from a sorted mutable sequence.
How it connects
Connects lexicographic ordering with permutations, duplicate handling, Fisher–Yates shuffling, and direct permutation generation.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Fabulous Adventures in Data Structures and Algorithms. The section links point to the parts of the book it draws on.