Solving Leetcode Interviews in Seconds with AI: Previous Permutation With One Swap
Introduction
In this blog post, we will explore how to solve the LeetCode problem "1053" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
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] Example 1: Input: arr = [3,2,1] Output: [3,1,2] Explanation: Swapping 2 and 1. Example 2: Input: arr = [1,1,5] Output: [1,1,5] Explanation: This is already the smallest permutation. Example 3: Input: arr = [1,9,4,6,7] Output: [1,7,4,6,9] Explanation: Swapping 9 and 7. Constraints: 1 <= arr.length <= 104 1 <= arr[i] <= 104
Explanation
Here's the breakdown of the solution:
- Find the Pivot: Start from the right and find the first element
arr[i]which is greater than the element to its rightarr[i+1]. Thisarr[i]is our pivot. If no such element is found, the array is already in ascending order (lexicographically smallest), so return the original array. - Find the Swap Element: Find the largest element
arr[j]to the right of the pivot that is smaller than the pivot. Swap and Return: Swap
arr[i]andarr[j]and return the modified array.Time Complexity: O(n), where n is the length of the array. Space Complexity: O(1)
Code
def prevPermOpt1(arr):
n = len(arr)
# Find the pivot
for i in range(n - 2, -1, -1):
if arr[i] > arr[i + 1]:
# Find the largest element to the right of the pivot that is smaller than the pivot
j = n - 1
while arr[j] >= arr[i] or arr[j] == arr[j - 1]:
j -= 1
# Swap arr[i] and arr[j]
arr[i], arr[j] = arr[j], arr[i]
return arr
# If no such element is found, the array is already in ascending order
return arr