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 - Space Optimized DP INPUT Integer Array nums[] 1 i=0 2 i=1 3 i=2 4 i=3 Common difference = 1 +1 +1 +1 Arithmetic Subarray: - At least 3 elements - Same difference between consecutive elements nums = [1, 2, 3, 4] Length = 4 ALGORITHM STEPS 1 Initialize dp = 0, total = 0 2 Iterate from i=2 Check if arithmetic 3 If diff matches: dp = dp + 1 total += dp 4 Else: dp = 0 Reset counter Iteration Trace: i dp total Slice 2 1 1 [1,2,3] 3 2 3 [2,3,4] [1,2,3,4] FINAL RESULT Found 3 Arithmetic Subarrays: Slice 1: [1, 2, 3] diff = 1, length = 3 Slice 2: [2, 3, 4] diff = 1, length = 3 Slice 3: [1, 2, 3, 4] diff = 1, length = 4 Output: 3 Total Count OK - Result verified! Key Insight: Space Optimized DP uses only O(1) space! When we extend an arithmetic sequence by one element, it creates (dp + 1) new arithmetic slices. If sequence breaks, reset dp to 0. The variable 'dp' tracks consecutive arithmetic triplets ending at current position. Total accumulates all valid slices. TutorialsPoint - Arithmetic Slices | Space Optimized DP Approach
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