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
๐ŸŽต Arithmetic Slices: Musical Pattern Recognition๐ŸŽผ Beat Pattern: [1, 3, 5, 7, 9]13579+2+2+2+2๐Ÿงฎ DP Calculation:Position 2 (value 5): Arithmetic sequence starts โ†’ length = 1 โ†’ +1 slicePosition 3 (value 7): Continues sequence โ†’ length = 2 โ†’ +2 slicesPosition 4 (value 9): Continues sequence โ†’ length = 3 โ†’ +3 slices๐ŸŽฏ Total: 1 + 2 + 3 = 6 arithmetic slices๐ŸŽช All Found Slices:[1,3,5] [3,5,7] [5,7,9] โ† Length 3 slices[1,3,5,7] [3,5,7,9] โ† Length 4 slices[1,3,5,7,9] โ† Length 5 slice
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

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only need to track current sequence length, no extra arrays needed

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 5000
  • -1000 โ‰ค nums[i] โ‰ค 1000
  • Arithmetic slice requires at least 3 elements
Asked in
Google 42 Amazon 38 Meta 29 Microsoft 24
42.4K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen