The Previous Permutation With One Swap problem asks you to find the lexicographically largest permutation that is strictly smaller than the current one, achievable by exactly one swap of two elements. This coding problem uses a greedy right-to-left scan to find the optimal swap. The array and greedy interview pattern is the core.
Microsoft and Meta ask this as a variant of the Next Permutation problem — but in reverse direction. It tests whether candidates can adapt the standard permutation algorithm to find the previous rather than next permutation with a single swap constraint.
Right-to-left scan + greedy swap. From right to left, find the first index i where arr[i] > arr[i+1] (descending). Then find the rightmost index j > i where arr[j] < arr[i] and arr[j] is not equal to any previous arr[j] for same value (pick leftmost of equal smaller values). Swap arr[i] and arr[j].
arr=[3,2,1]. Find first descending: i=1 (arr[1]=2 > arr[2]=1). Find largest j > 1 where arr[j] < arr[1]=2: j=2 (value 1). Swap: [3,1,2]. Result: [3,1,2].
arr=[1,9,4,6,7]. First descending: i=2 (arr[2]=4 < arr[3]=6? No, arr[3]=6>arr[4]=7? No, arr[2]=4 < arr[3]=6 not descending... Let me recheck: find where arr[i] > arr[i+1]. arr[3]=6 < arr[4]=7: no. arr[2]=4 < arr[3]=6: no. arr[1]=9 > arr[2]=4: yes, i=1). Find rightmost j > 1 where arr[j] < 9 and largest: j=4 (7). Swap: [1,7,4,6,9]. Result: [1,7,4,6,9].
Previous Permutation With One Swap is the complement of Next Permutation. While next permutation finds a rightmost ascending pair (left of which has a smaller element), previous permutation finds a rightmost descending step (where a larger element sits left of smaller). Practice both together. The "rightmost" constraint for previous permutation ensures you make the minimal decrease needed for the largest possible previous permutation.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Transform Array to All Equal Elements | Medium | Solve | |
| Minimum Domino Rotations For Equal Row | Medium | Solve | |
| Reach End of Array With Max Score | Medium | Solve | |
| Increasing Triplet Subsequence | Medium | Solve | |
| Maximum Distance in Arrays | Medium | Solve |