Previous Permutation With One Swap - Problem

Given an array of positive integers arr (not necessarily distinct), return the lexicographically largest permutation that is smaller than arr, that can be made with exactly one swap.

If it cannot be done, then return the same array.

Note that a swap exchanges the positions of two numbers arr[i] and arr[j]

Input & Output

Example 1 — Basic Swap Case
$ Input: arr = [3,2,1]
Output: [3,1,2]
💡 Note: Find rightmost decreasing position (i=1, where 2>1), then find largest smaller element to the right (j=2, value=1). Swap positions 1 and 2 to get [3,1,2].
Example 2 — No Swap Possible
$ Input: arr = [1,1,5]
Output: [1,1,5]
💡 Note: Array is already in non-decreasing order from left to right. No position i exists where arr[i] > arr[i+1], so no swap is possible.
Example 3 — Multiple Candidates
$ Input: arr = [1,9,4,6,7]
Output: [1,7,4,6,9]
💡 Note: Rightmost decreasing position is i=1 (9>4). Among elements to the right that are smaller than 9, we choose the largest one which is 7 at position 4. Swap to get [1,7,4,6,9].

Constraints

  • 1 ≤ arr.length ≤ 104
  • 1 ≤ arr[i] ≤ 104

Visualization

Tap to expand
Previous Permutation With One Swap INPUT arr = [3, 2, 1] 3 i=0 2 i=1 1 i=2 Goal: Find largest permutation smaller than current array Constraint: Exactly ONE swap allowed ALGORITHM STEPS 1 First Pass (Right to Left) Find i where arr[i] > arr[i+1] i=1: arr[1]=2 > arr[2]=1 OK 2 Second Pass Find largest j where arr[j] < arr[i], j > i j=2: arr[2]=1 < arr[1]=2 3 Perform Swap Swap arr[i] and arr[j] Swap arr[1] <--> arr[2] 2 1 4 Return Result Array after one swap FINAL RESULT Output: [3, 1, 2] 3 1 2 Swapped positions Verification: [3,1,2] < [3,2,1] -- OK Lexicographically smaller and largest possible Comparison: Before: 3, 2, 1 After: 3, 1, 2 One swap used -- OK Key Insight: To get the largest permutation smaller than current, we need to find the rightmost position where we can make the array smaller. We look for arr[i] > arr[i+1] from right, then swap arr[i] with the largest element to its right that is still smaller than arr[i]. This greedy approach ensures the optimal result. TutorialsPoint - Previous Permutation With One Swap | Greedy Two-Pass Approach
Asked in
Google 25 Microsoft 18 Amazon 12
35.0K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen