Solving Leetcode Interviews in Seconds with AI: Minimum Right Shifts to Sort the Array
Introduction
In this blog post, we will explore how to solve the LeetCode problem "2855" 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
You are given a 0-indexed array nums of length n containing distinct positive integers. Return the minimum number of right shifts required to sort nums and -1 if this is not possible. A right shift is defined as shifting the element at index i to index (i + 1) % n, for all indices. Example 1: Input: nums = [3,4,5,1,2] Output: 2 Explanation: After the first right shift, nums = [2,3,4,5,1]. After the second right shift, nums = [1,2,3,4,5]. Now nums is sorted; therefore the answer is 2. Example 2: Input: nums = [1,3,5] Output: 0 Explanation: nums is already sorted therefore, the answer is 0. Example 3: Input: nums = [2,1,4] Output: -1 Explanation: It's impossible to sort the array using right shifts. Constraints: 1 <= nums.length <= 100 1 <= nums[i] <= 100 nums contains distinct integers.
Explanation
- The core idea is to iterate through all possible right shifts of the input array
nums.- For each shift, check if the shifted array is sorted. If sorted, return the number of shifts performed.
- If none of the shifts result in a sorted array, return -1.
- Time Complexity: O(n^2), where n is the length of the array. Space Complexity: O(n).
Code
def minimum_right_shifts(nums):
"""
Finds the minimum number of right shifts required to sort an array.
Args:
nums: A 0-indexed array of distinct positive integers.
Returns:
The minimum number of right shifts required to sort the array, or -1 if impossible.
"""
n = len(nums)
for shifts in range(n):
shifted_nums = nums[:] # Create a copy to avoid modifying the original
for _ in range(shifts):
temp = shifted_nums[-1]
for i in range(n - 1, 0, -1):
shifted_nums[i] = shifted_nums[i - 1]
shifted_nums[0] = temp
is_sorted = all(shifted_nums[i] <= shifted_nums[i+1] for i in range(n-1))
if is_sorted:
return shifts
return -1