MediumNo. 0413
Arithmetic Slices — LeetCode 413 Python Solution
- Pattern
- Sliding Window
- Topics
- Array, Dynamic Programming, Sliding Window
- Reading time
- 2 min
- Source
- leetcode.com
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
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 ansComplexity
- Time
- O(n)
- Space · auxiliary
- O(1)
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
| No. | Problem | Difficulty |
|---|---|---|
| 0446 | Arithmetic Slices II - Subsequence | Hard |
| 0689 | Maximum Sum of 3 Non-Overlapping Subarrays | Hard |
| 0978 | Longest Turbulent Subarray | Medium |
| 1031 | Maximum Sum of Two Non-Overlapping Subarrays | Medium |
| 1425 | Constrained Subsequence Sum | Hard |
| 1493 | Longest Subarray of 1's After Deleting One Element | Medium |
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.