Arithmetic Slices - Problem
An arithmetic slice is like finding patterns in sequences! Given an integer array, we need to count how many contiguous subarrays form arithmetic progressions.
An arithmetic sequence requires:
- At least 3 elements
- Constant difference between consecutive elements
For example, in [1,3,5,7,9], the difference is always 2. In [7,7,7,7], the difference is 0. Even [3,-1,-5,-9] works with difference -4!
Goal: Count all possible arithmetic subarrays of length โฅ 3 in the given array.
Input: An integer array nums
Output: Total number of arithmetic subarrays
Input & Output
example_1.py โ Basic Arithmetic Sequence
$
Input:
[1,2,3,4]
โบ
Output:
3
๐ก Note:
Three arithmetic slices: [1,2,3], [2,3,4], and [1,2,3,4]. All have common difference of 1.
example_2.py โ Single Arithmetic Slice
$
Input:
[1,3,5,7,9]
โบ
Output:
6
๐ก Note:
Six slices with difference 2: [1,3,5], [3,5,7], [5,7,9], [1,3,5,7], [3,5,7,9], [1,3,5,7,9].
example_3.py โ No Arithmetic Slices
$
Input:
[1,2,4,8]
โบ
Output:
0
๐ก Note:
No arithmetic slices possible as differences are not constant: 1, 2, 4 respectively.
Visualization
Tap to expand
Understanding the Visualization
1
Identify Pattern Start
Find where arithmetic sequence begins (when 3 consecutive elements have same difference)
2
Track Pattern Length
Continue counting while the pattern holds, reset when it breaks
3
Calculate Contributions
Each position in a sequence of length L contributes L new slices ending at that position
Key Takeaway
๐ฏ Key Insight: Instead of checking every subarray, track the length of current arithmetic sequence. When sequence length is L, it contributes L new slices ending at current position!
Time & Space Complexity
Time Complexity
O(n)
Single pass through the array, constant work per element
โ Linear Growth
Space Complexity
O(1)
Only need to track current sequence length, no extra arrays needed
โ Linear Space
Constraints
- 1 โค nums.length โค 5000
- -1000 โค nums[i] โค 1000
- Arithmetic slice requires at least 3 elements
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code