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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code