Knowledge Guide
HomeDSACompany Practice

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:

Example 2:

Example 3:

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

  1. Initialization: Start by checking if the input array nums has fewer than 3 elements. If yes, return 0 immediately since at least three elements are needed to form an arithmetic slice.

  2. Setup Counters: Initialize two counters: count to store the total number of arithmetic slices found, and consecutive to track the length of the current consecutive arithmetic slice sequence.

  3. 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.

  4. 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.

  5. Update Counters: If the current set of elements continues an arithmetic sequence, increment the consecutive counter by 1. Then, add the value of consecutive to count. This step accounts for the number of new arithmetic slices that include the current element.

  6. Reset consecutive if Needed: If the current set of elements does not continue an arithmetic sequence, reset the consecutive counter to 0. This prepares it for the next sequence of arithmetic slices.

  7. Complete Iteration and Return: Continue steps 4 through 6 for each element in the array. After completing the iteration, return the total count of arithmetic slices found.

Algorithm Walkthrough

Let's consider the Input: nums = [1, 3, 5, 7, 9, 10, 11]

  1. Initialization: The input array has more than 3 elements, so we proceed.

  2. Setup Counters: Initialize count = 0 and consecutive = 0.

  3. First Iteration (i = 2, Element = 5):

    • Calculate differences: 5 - 3 = 2 and 3 - 1 = 2. They are equal.
    • Increment consecutive to 1.
    • Add consecutive to count (count = 1).
  4. Second Iteration (i = 3, Element = 7):

    • Differences: 7 - 5 = 2 and 5 - 3 = 2. Still equal.
    • Increment consecutive to 2.
    • Add consecutive to count (count = 3).
  5. Third Iteration (i = 4, Element = 9):

    • Differences: 9 - 7 = 2 and 7 - 5 = 2. Equal again.
    • Increment consecutive to 3.
    • Add consecutive to count (count = 6).
  6. Fourth Iteration (i = 5, Element = 10):

    • Differences: 10 - 9 = 1 and 9 - 7 = 2. Not equal.
    • Reset consecutive to 0.
  7. Fifth Iteration (i = 6, Element = 11):

    • Differences: 11 - 10 = 1 and 10 - 9 = 1. Equal.
    • Increment consecutive to 1.
    • Add consecutive to count (count = 7).
  8. Completion: After completing the iteration, we find that the total count of arithmetic slices is 7.

Code

java
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 , where n is the number of elements in the input array 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 . This is because the amount of extra space used does not depend on the size of the input array.

🤖 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.

🪜 Hint ladder (no spoilers)

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.
🎨 Explain the approach visually

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.
🔍 Review my solution

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.
🔁 Drill the pattern

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.

📝 My notes