LeetCode 1053: Previous Permutation With One Swap Solution

Master LeetCode problem 1053 (Previous Permutation With One Swap), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1053. Previous Permutation With One Swap

Problem Explanation

Explanation

To find the lexicographically largest permutation that is smaller than the given array with exactly one swap, we can start from the end of the array and find the first pair of elements where the first element is greater than the second element. This is the element that we need to swap to get the desired permutation. After finding this pair, we need to find the largest element to the left of this pair that is smaller than the second element in the pair. We swap these two elements to get the final result.

  • Start from the end of the array and find the first pair (i, j) where arr[i] > arr[j].
  • Find the largest element k to the left of j such that arr[k] < arr[j].
  • Swap arr[k] and arr[j] to get the final result.

Time Complexity: O(n) where n is the number of elements in the array. Space Complexity: O(1)

Solution Code

class Solution {
    public int[] prevPermOpt1(int[] arr) {
        int i = arr.length - 2;
        while (i >= 0 && arr[i] <= arr[i + 1]) {
            i--;
        }
        
        if (i >= 0) {
            int j = arr.length - 1;
            while (arr[j] >= arr[i] || arr[j] == arr[j - 1]) {
                j--;
            }
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
        
        return arr;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1053 (Previous Permutation With One Swap)?

This page provides optimized solutions for LeetCode problem 1053 (Previous Permutation With One Swap) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1053 (Previous Permutation With One Swap)?

The time complexity for LeetCode 1053 (Previous Permutation With One Swap) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1053 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1053 in Java, C++, or Python.

Back to LeetCode Solutions