Arithmetic Subarrays — LeetCode 1630 Python Solution

MediumArrayHash TableSorting
Problem
#1630
Pattern
Sorting
Reading time
2 min

The problem

A sequence of numbers is called arithmetic if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence s is arithmetic if and only if s[i+1] - s[i] == s[1] - s[0] for all valid i.

Example

1, 3, 5, 7, 9
7, 7, 7, 7
3, -1, -5, -9

Python solution

Python
class Solution:
    def checkArithmeticSubarrays(
        self, nums: List[int], l: List[int], r: List[int]
    ) -> List[bool]:
        def check(nums, l, r):
            n = r - l + 1
            s = set(nums[l : l + n])
            a1, an = min(nums[l : l + n]), max(nums[l : l + n])
            d, mod = divmod(an - a1, n - 1)
            return mod == 0 and all((a1 + (i - 1) * d) in s for i in range(1, n))

        return [check(nums, left, right) for left, right in zip(l, r)]

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Sorting

Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 1630. Arithmetic Subarrays is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.

The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1630. Arithmetic Subarrays?
LeetCode 1630. Arithmetic Subarrays is rated Medium on LeetCode.
What is the time complexity of LeetCode 1630. Arithmetic Subarrays?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1630. Arithmetic Subarrays?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1630. Arithmetic Subarrays cover?
LeetCode 1630. Arithmetic Subarrays is tagged Array, Hash Table and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview