VOOZH about

URL: https://www.geeksforgeeks.org/dsa/lexicographically-previous-permutation-in-c/

⇱ Lexicographically Previous Permutation - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Lexicographically Previous Permutation

Last Updated : 3 Jun, 2026

Given a string s representing a non-negative integer, find the lexicographically previous permutation of its digits. Each digit of s must be used exactly once, and the resulting number must not contain leading zeros.

  • If no previous permutation exists, return "-1".
  • The answer should be returned as a string.

Examples:

Input: s = "4321"
Output: "4312"
Explanation:The lexicographically previous permutation of "4321" is "4312".

Input: s = "1234"
Output: "-1"
Explanation: The string "1234" is sorted in ascending order, so no previous permutation exists.

[Naive Approach] Generate All Permutations - O(|s| × |s|!) Time and O(|s|) Space

The idea is to generate all possible permutations of the digits of s using recursion (backtracking). For each permutation, we check whether it is valid,. Among all valid permutations, we keep track of the largest one. If no valid permutation exists, return “-1”.


Output
4312

[Expected Approach] Previous Permutation - O(|s|) Time and O(1) Space

Instead of generating all permutations, we directly construct the previous permutation. We first find the pivot, the first index from the right where s[i] > s[i+1]. This is the point where the number can be reduced.

  • Find the first index i from right such that s[i] > s[i+1]
  • If not found, return "-1"
  • Find the largest digit smaller than s[i] on the right
  • Swap pivot with that digit (avoid leading zero if i == 0)
  • Reverse suffix from i + 1 and return result

Consider the input: s = "534976"

Step 1: Traverse from right and find the first index i such that s[i] > s[i + 1].

  • Scan from right: 5 3 4 9 7 6 . Here, 7 > 6, so pivot index = 4 and pivot digit = 7.
  • This is the position where the number can be made smaller.

Step 2: From the right side of pivot, find the largest digit smaller than pivot digit.

  • Right side = [6]
  • The largest digit smaller than 7 is 6.

Step 3: Swap the pivot digit with the selected digit.

  • Before Swap: 5 3 4 9 7 6
  • After Swap: 5 3 4 9 6 7

Step 4: Reverse the suffix after the pivot. Since the suffix is already in increasing order, reversing it makes it descending and gives the largest possible arrangement.

  • Suffix = [7]
  • Since the suffix contains only one digit, it remains unchanged.

Step 5: The resulting string is: 534967

Therefore, the lexicographically previous permutation of "534976" is: 534967


Output
534967
Comment