> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Arithmetic Slices Python Solution with Tests

> Tested Python solution for LeetCode 413 with 22 pytest cases. Generate a practice environment with lcpy.

LeetCode 413, [Medium](/catalog/medium). Topics: [Array](/catalog/topics/array), [Dynamic Programming](/catalog/topics/dynamic-programming), [Sliding Window](/catalog/topics/sliding-window). [View on LeetCode](https://leetcode.com/problems/arithmetic-slices/description/).

Generate this problem as a practice environment: tested reference solution, 22 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 413   # by problem number
lcpy gen -s arithmetic_slices   # by problem name
```

## 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.

Given an integer array `nums`, return the number of arithmetic subarrays of `nums`.

A subarray is a contiguous subsequence of the array.

### Examples

```
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.
```

```
Input: nums = [1]
Output: 0
```

### Constraints

* 1 \<= nums.length \<= 5000
* -1000 \<= nums\[i] \<= 1000

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/arithmetic_slices/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/arithmetic_slices/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n)
    # Space: O(1)
    def number_of_arithmetic_slices(self, nums: list[int]) -> int:
        total = 0
        run = 0
        for i in range(2, len(nums)):
            if nums[i] - nums[i - 1] == nums[i - 1] - nums[i - 2]:
                run += 1
                total += run
            else:
                run = 0
        return total
```

## Complexity

| Time | Space |
| - | - |
| O(n) | O(1) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.