Ctrl K

One Swap Back

Medium
You are given an array of positive integers values (values may repeat). You may swap exactly two elements, once. Among all arrays that such a swap produces and that are **lexicographically smaller** than the original, find the largest one and return it. In other words, you want the nearest arrangement below the current one that is reachable in a single swap. If no swap makes the array smaller, return values unchanged.
Example 1
values=[2, 7, 5, 8] → [2, 5, 7, 8]

Swap 7 and 5 to get [2, 5, 7, 8]. It is the only swap that makes the array smaller than the original.

Example 2
values=[6, 3, 4, 4] → [4, 3, 6, 4]

Only the first element can go down. The largest smaller value to its right is 4; take the first of the two 4s, otherwise the result would be smaller: [4, 3, 6, 4].

Example 3
values=[1, 2, 2, 9] → [1, 2, 2, 9]

The array is already non-decreasing, so every swap would only make it larger; it is returned unchanged.

Constraints
  • 1 ≤ len(values) ≤ 10⁴
  • 1 ≤ values[i] ≤ 10⁴
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTwo Boards Holding Water MediumFewest Jumps to the End MediumReach the Last Cell MediumAs Many Trades as You Like MediumWhere to Start the Lap Medium
loading Python…
Input
values=[2, 7, 5, 8]
Expected
[2, 5, 7, 8]

Run checks the first 3 tests in your browser. Submit checks all 132 tests on the server, hidden ones included.