#413
Medium Algorithms Arithmetic slices
Array Dynamic Programming Sliding Window
64.8% acceptance
Jan 13, 2026
5625
306
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.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn number_of_arithmetic_slices(nums: Vec<i32>) -> i32 {
if nums.len() < 3 {
return 0;
}
let mut count = 0;
let mut current = 0;
for i in 2..nums.len() {
if nums[i] - nums[i - 1] == nums[i - 1] - nums[i - 2] {
current += 1;
count += current;
} else {
current = 0;
}
}
count
}
}