Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Check if Array Is Sorted and Rotated

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "1752" 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 nums, return true if the array was originally sorted in non-decreasing order, then rotated some number of positions (including zero). Otherwise, return false. There may be duplicates in the original array. Note: An array A rotated by x positions results in an array B of the same length such that B[i] == A[(i+x) % A.length] for every valid index i. Example 1: Input: nums = [3,4,5,1,2] Output: true Explanation: [1,2,3,4,5] is the original sorted array. You can rotate the array by x = 3 positions to begin on the element of value 3: [3,4,5,1,2]. Example 2: Input: nums = [2,1,3,4] Output: false Explanation: There is no sorted array once rotated that can make nums. Example 3: Input: nums = [1,2,3] Output: true Explanation: [1,2,3] is the original sorted array. You can rotate the array by x = 0 positions (i.e. no rotation) to make nums. Constraints: 1 <= nums.length <= 100 1 <= nums[i] <= 100

Explanation

Here's a breakdown of the approach, followed by the Python code:

  • Find the Potential Rotation Point: Iterate through the array to find an index where nums[i] > nums[i+1]. This indicates a potential rotation point. If no such point exists, the array is already sorted (or has a single element) and thus a rotated sorted array.
  • Verify Sorted Order Around Rotation Point: Once a potential rotation point is found, check if the array is sorted before the rotation point and after the rotation point. Also ensure the last element is <= first element (after the potential rotation).
  • Handle Edge Cases: Consider cases where the array is already sorted (no rotation required) or when the rotation point is at the end of the array.

  • Time Complexity: O(n), where n is the length of the input array.

  • Space Complexity: O(1)

Code

    def check(nums):
    """
    Checks if an array is a rotated sorted array.

    Args:
        nums: A list of integers.

    Returns:
        True if the array is a rotated sorted array, False otherwise.
    """
    n = len(nums)
    k = 0  # Count of decreases indicating rotation
    for i in range(n):
        if nums[i] > nums[(i + 1) % n]:
            k += 1

    return k <= 1

More from this blog

C

Chatmagic blog

2894 posts