Arithmetic Slices — LeetCode 413 Python Solution

MediumArrayDynamic ProgrammingSliding Window
Problem
#413
Reading time
2 min

The problem

An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same. For example, [1,3,5,7,9], [7,7,7,7], and [3,-1,-5,-9] are arithmetic sequences.

Example

Input
nums = [1,2,3,4]
Output
3
Explanation
We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself.

Python solution

Python
class Solution:
    def numberOfArithmeticSlices(self, nums: List[int]) -> int:
        ans = cnt = 0
        d = 3000
        for a, b in pairwise(nums):
            if b - a == d:
                cnt += 1
            else:
                d = b - a
                cnt = 0
            ans += cnt
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(1) auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 413. Arithmetic Slices is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.

The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 413. Arithmetic Slices?
LeetCode 413. Arithmetic Slices is rated Medium on LeetCode.
What is the time complexity of LeetCode 413. Arithmetic Slices?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 413. Arithmetic Slices?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 413. Arithmetic Slices cover?
LeetCode 413. Arithmetic Slices is tagged Array, Dynamic Programming and Sliding Window 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