Arithmetic Slices - 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.
Input & Output
Example 1 — Basic Arithmetic Sequence
$
Input:
nums = [1,2,3,4]
›
Output:
3
💡 Note:
Three arithmetic slices: [1,2,3] (diff=1), [2,3,4] (diff=1), and [1,2,3,4] (diff=1)
Example 2 — Constant Sequence
$
Input:
nums = [1,1,1,1]
›
Output:
3
💡 Note:
Three arithmetic slices with diff=0: [1,1,1] at positions 0-2, [1,1,1] at positions 1-3, and [1,1,1,1] at positions 0-3
Example 3 — No Arithmetic Slices
$
Input:
nums = [1,2,4]
›
Output:
0
💡 Note:
Only one possible subarray [1,2,4], but differences are 1 and 2, so not arithmetic
Constraints
- 1 ≤ nums.length ≤ 5000
- -1000 ≤ nums[i] ≤ 1000
Visualization
Tap to expand
Understanding the Visualization
1
Input Analysis
Array [1,2,3,4] with consistent differences
2
Find Patterns
Identify arithmetic sequences of length ≥3
3
Count Slices
Total arithmetic subarrays found
Key Takeaway
🎯 Key Insight: Each time we extend an arithmetic sequence, we create multiple new slices at once
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code