Pattern avoidance in permutations is a long studied topic in combinatorics and computer science. A permutation p1,p2,…,pn of the natural numbers 1,…,n avoids the 3-1-2 pattern if there are no indices 1≤i<j<k≤n with pi>pj, pi>pk and pj<pk.
List every permutation of 1,…,n that avoids the 3-1-2 pattern in lexicographic order. Given one permutation from that list, compute the permutation that follows it. The decreasing sequence n,n−1,…,1 is the last entry of the list, and the input is never that permutation, so the answer always exists.