How to find Lexicographically previous permutation ? | C # program to print all permutations with duplicates allowed using prev_permutation ( ) ; Function to compute the previous permutation ; Find index of the last element of the string ; Find largest index i such that str [ i - 1 ] > str [ i ] ; if string is sorted in ascending order we 're  at the last permutation ; Note - str [ i . . n ] is sorted in ascending order Find rightmost element 's index  that is less than str[i - 1] ; Swap character at i - 1 with j ; Reverse the substring [ i . . n ] ; Utililty function to swap ; Utility function to reverse ; Driver code
using System ; class GFG { static Boolean prevPermutation ( char [ ] str ) { int n = str . Length - 1 ; int i = n ; while ( i > 0 && str [ i - 1 ] <= str [ i ] ) { i -- ; } if ( i <= 0 ) { return false ; } int j = i - 1 ; while ( j + 1 <= n && str [ j + 1 ] <= str [ i - 1 ] ) { j ++ ; } swap ( str , i - 1 , j ) ; String sb = String . Join ( " " , str ) ; sb = reverse ( sb ) ; str = sb . ToString ( ) . ToCharArray ( ) ; return true ; } static String swap ( char [ ] ch , int i , int j ) { char temp = ch [ i ] ; ch [ i ] = ch [ j ] ; ch [ j ] = temp ; return String . Join ( " " , ch ) ; } static String reverse ( String input ) { char [ ] temparray = input . ToCharArray ( ) ; int left , right = 0 ; right = temparray . Length - 1 ; for ( left = 0 ; left < right ; left ++ , right -- ) { char temp = temparray [ left ] ; temparray [ left ] = temparray [ right ] ; temparray [ right ] = temp ; } return String . Join ( " " , temparray ) ; } public static void Main ( String [ ] args ) { char [ ] str = "4321" . ToCharArray ( ) ; if ( prevPermutation ( str ) ) { Console . WriteLine ( " Previous ▁ permutation ▁ is ▁ " + String . Join ( " " , str ) ) ; } else { Console . WriteLine ( " Previous ▁ permutation " + " doesn ' t ▁ exist " ) ; } } }