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
Arithmetic Slices: Count Subarrays with Consistent Differences1234+1+1+1Arithmetic Subarrays Found:1. [1,2,3] - length 3, diff=12. [2,3,4] - length 3, diff=13. [1,2,3,4] - length 4, diff=1Total Count: 3All differences are +1 (consistent)Output: 3
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
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
87.5K Views
Medium Frequency
~15 min Avg. Time
3.2K 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