Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Can Make Arithmetic Progression From Sequence

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "1502" 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

A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same. Given an array of numbers arr, return true if the array can be rearranged to form an arithmetic progression. Otherwise, return false. Example 1: Input: arr = [3,5,1] Output: true Explanation: We can reorder the elements as [1,3,5] or [5,3,1] with differences 2 and -2 respectively, between each consecutive elements. Example 2: Input: arr = [1,2,4] Output: false Explanation: There is no way to reorder the elements to obtain an arithmetic progression. Constraints: 2 <= arr.length <= 1000 -106 <= arr[i] <= 106

Explanation

Here's the solution:

  • Sort the array: Sorting allows us to easily check if the difference between consecutive elements is constant.
  • Calculate the common difference: Find the difference between the first two elements after sorting. This will be our potential common difference.
  • Verify the progression: Iterate through the sorted array, checking if the difference between each consecutive pair of elements matches the calculated common difference.

  • Runtime Complexity: O(n log n) due to sorting. Storage Complexity: O(1) or O(n) depending on the sorting algorithm implementation (in-place or not). Python's sort() is typically Timsort, which has O(n) space complexity in the worst case but often operates in O(1).

Code

    def canMakeArithmeticProgression(arr):
    """
    Checks if an array can be rearranged to form an arithmetic progression.

    Args:
        arr: A list of numbers.

    Returns:
        True if the array can be rearranged to form an arithmetic progression, False otherwise.
    """
    arr.sort()
    if len(arr) < 2:
        return True  # An array with fewer than 2 elements is trivially an arithmetic progression

    diff = arr[1] - arr[0]
    for i in range(2, len(arr)):
        if arr[i] - arr[i - 1] != diff:
            return False

    return True

More from this blog

C

Chatmagic blog

2894 posts