Leetcode 1053: Previous Permutation With One Swap

grid47
grid47
Exploring patterns and algorithms
Jul 24, 2024 6 min read

Given an array of positive integers, return the lexicographically largest permutation that is smaller than the given array. This can be done by swapping exactly two elements. If no such swap is possible (i.e., the array is already the smallest permutation), return the same array.
Problem
Approach
Steps
Complexity
Input: You are given an array of integers arr where each element is a positive integer. You need to return the lexicographically largest permutation smaller than arr that can be made by swapping exactly two numbers in the array.
Example: Input: arr = [5, 3, 4, 2, 1]
Constraints:
• 1 <= arr.length <= 10^4
• 1 <= arr[i] <= 10^4
Output: The output should be the lexicographically largest permutation that is smaller than the given array, obtained by swapping exactly two elements. If no such swap exists, return the input array as is.
Example: Output: [5, 4, 3, 2, 1]
Constraints:
• The output is guaranteed to be a valid array of integers.
Goal: The goal is to find the lexicographically largest permutation smaller than the given array by swapping two elements.
Steps:
• 1. Find the first pair of adjacent elements where arr[i] > arr[i+1] (this is where the lexicographical order breaks).
• 2. Swap the first element arr[i] with the largest element in the suffix of the array that is smaller than arr[i].
• 3. If no such pair exists, return the array as is, because it is already the smallest permutation.
Goal: The array contains positive integers and its length is constrained as described below.
Steps:
• 1 <= arr.length <= 10^4
• 1 <= arr[i] <= 10^4
Assumptions:
• The array contains positive integers and the length of the array is between 1 and 10,000.
Input: Input: arr = [5, 3, 4, 2, 1]
Explanation: The largest permutation smaller than [5, 3, 4, 2, 1] is obtained by swapping 3 and 4, resulting in [5, 4, 3, 2, 1].

Input: Input: arr = [1, 2, 3]
Explanation: Since the array is already in ascending order, no swap can make a smaller permutation. Therefore, the output is the same as the input: [1, 2, 3].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus