medium Arithmetic Slices
Problem Statement
Given an integer array nums, return the number of arithmetic subarrays of nums.
If any integer array consists of at least three elements and if the difference between any two consecutive elements is the same, it is called arithmetic.
A subarray is a contiguous subsequence of the array.
Examples
Example 1:
- Input:
[1, 3, 5, 7, 9, 10, 11] - Expected Output:
7 - Justification: The segments that form arithmetic sequences are
[1, 3, 5],[3, 5, 7],[5, 7, 9],[1, 3, 5, 7],[3, 5, 7, 9],[1, 3, 5, 7, 9], and[9, 10, 11]. Each of these segments has a constant difference of 2 between consecutive elements.
Example 2:
- Input:
[7, 7, 7, 7] - Expected Output:
3 - Justification: The qualifying segments are
[7, 7, 7],[7, 7, 7, 7](considering the first three and then all four elements), and the last three elements[7, 7, 7]. Each segment has a constant difference of 0 between its elements.
Example 3:
- Input:
[1, 2, 4, 6, 8] - Expected Output:
3 - Justification: Only three segments
[2,4,6],[4, 6, 8]and[2, 4, 6, 8]form arithmetic sequences with a constant difference of 2.
Try it yourself
Try solving this question here:
✅ Solution Arithmetic Slices
Problem Statement
Given an integer array nums, return the number of arithmetic subarrays of nums.
If any integer array consists of at least three elements and if the difference between any two consecutive elements is the same, it is called arithmetic.
A subarray is a contiguous subsequence of the array.
Examples
Example 1:
- Input:
[1, 3, 5, 7, 9, 10, 11] - Expected Output:
7 - Justification: The segments that form arithmetic sequences are
[1, 3, 5],[3, 5, 7],[5, 7, 9],[1, 3, 5, 7],[3, 5, 7, 9],[1, 3, 5, 7, 9], and[9, 10, 11]. Each of these segments has a constant difference of 2 between consecutive elements.
Example 2:
- Input:
[7, 7, 7, 7] - Expected Output:
3 - Justification: The qualifying segments are
[7, 7, 7],[7, 7, 7, 7](considering the first three and then all four elements), and the last three elements[7, 7, 7]. Each segment has a constant difference of 0 between its elements.
Example 3:
- Input:
[1, 2, 4, 6, 8] - Expected Output:
3 - Justification: Only three segments
[2,4,6],[4, 6, 8]and[2, 4, 6, 8]form arithmetic sequences with a constant difference of 2.
Solution
To solve this problem, we will iterate through the array while keeping track of the current arithmetic sequence's length. The approach hinges on understanding that for any arithmetic sequence with more than three elements, it inherently contains smaller arithmetic sequences. For instance, a sequence of four elements contains three smaller sequences. Thus, we calculate the total count of sequences as we identify them.
The rationale behind this approach is its efficiency and simplicity; it avoids unnecessary nested iterations, focusing instead on leveraging the arithmetic property of contiguous subarrays. This method is expected to work well because it directly counts sequences without explicitly enumerating all possible subarrays, thus optimizing both time and space complexity.
Step-by-Step Algorithm
-
Initialization: Start by checking if the input array
numshas fewer than 3 elements. If yes, return 0 immediately since at least three elements are needed to form an arithmetic slice. -
Setup Counters: Initialize two counters:
countto store the total number of arithmetic slices found, andconsecutiveto track the length of the current consecutive arithmetic slice sequence. -
Iterate Through Array: Begin iterating through the array starting from the third element (index 2), as the first two elements are used for initial comparison.
-
Check Arithmetic Sequence: For each element at index
i, check if the difference between the current element and the previous one (nums[i] - nums[i-1]) is the same as the difference between the previous element and the one before it (nums[i-1] - nums[i-2]). This checks if the current set of three elements forms part of an arithmetic sequence. -
Update Counters: If the current set of elements continues an arithmetic sequence, increment the
consecutivecounter by 1. Then, add the value ofconsecutivetocount. This step accounts for the number of new arithmetic slices that include the current element. -
Reset
consecutiveif Needed: If the current set of elements does not continue an arithmetic sequence, reset theconsecutivecounter to 0. This prepares it for the next sequence of arithmetic slices. -
Complete Iteration and Return: Continue steps 4 through 6 for each element in the array. After completing the iteration, return the total
countof arithmetic slices found.
Algorithm Walkthrough
Let's consider the Input: nums = [1, 3, 5, 7, 9, 10, 11]
-
Initialization: The input array has more than 3 elements, so we proceed.
-
Setup Counters: Initialize
count = 0andconsecutive = 0. -
First Iteration (i = 2, Element = 5):
- Calculate differences:
5 - 3 = 2and3 - 1 = 2. They are equal. - Increment
consecutiveto 1. - Add
consecutivetocount(count = 1).
- Calculate differences:
-
Second Iteration (i = 3, Element = 7):
- Differences:
7 - 5 = 2and5 - 3 = 2. Still equal. - Increment
consecutiveto 2. - Add
consecutivetocount(count = 3).
- Differences:
-
Third Iteration (i = 4, Element = 9):
- Differences:
9 - 7 = 2and7 - 5 = 2. Equal again. - Increment
consecutiveto 3. - Add
consecutivetocount(count = 6).
- Differences:
-
Fourth Iteration (i = 5, Element = 10):
- Differences:
10 - 9 = 1and9 - 7 = 2. Not equal. - Reset
consecutiveto 0.
- Differences:
-
Fifth Iteration (i = 6, Element = 11):
- Differences:
11 - 10 = 1and10 - 9 = 1. Equal. - Increment
consecutiveto 1. - Add
consecutivetocount(count = 7).
- Differences:
-
Completion: After completing the iteration, we find that the total
countof arithmetic slices is 7.
Code
import java.util.*;
public class Solution {
public int numberOfArithmeticSlices(int[] nums) {
if (nums.length < 3) return 0; // If array has fewer than 3 elements, no arithmetic slice is possible
int count = 0;
int consecutive = 0; // To keep track of consecutive arithmetic differences
for (int i = 2; i < nums.length; i++) {
if (nums[i] - nums[i - 1] == nums[i - 1] - nums[i - 2]) {
consecutive++; // Found an arithmetic sequence, increment the consecutive count
count += consecutive; // Add to total count, as consecutive sequences mean multiple slices
} else {
consecutive = 0; // Reset if current sequence is not arithmetic
}
}
return count;
}
public static void main(String[] args) {
Solution solution = new Solution();
// Example 1
System.out.println(
solution.numberOfArithmeticSlices(new int[] { 1, 3, 5, 7, 9, 10, 11 })
);
// Example 2
System.out.println(
solution.numberOfArithmeticSlices(new int[] { 7, 7, 7, 7 })
);
// Example 3
System.out.println(
solution.numberOfArithmeticSlices(new int[] { 1, 2, 4, 6, 8 })
);
}
}
Complexity Analysis
Time Complexity
The time complexity of the algorithm is nums. This is because the solution involves a single pass through the array to count arithmetic slices, with constant time operations performed for each element.
Space Complexity
The space complexity for the algorithm is
🤖 Don't fully get this? Learn it with Claude
Stuck on Arithmetic Slices? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Arithmetic Slices** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Arithmetic Slices** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Arithmetic Slices**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Arithmetic Slices**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.