HomeLeetcode413. Arithmetic Slices - Leetcode Solutions

413. Arithmetic Slices – Leetcode Solutions

Description

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.

subarray is a contiguous subsequence of the array.

Examples:

Example 1:

Input: nums = [1,2,3,4]
Output: 3
Explanation: We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself.

Example 2:

Input: nums = [1]
Output: 0

Solution in Python

Approach

  1. Identify Arithmetic Subarrays:
    • An array of at least three elements is arithmetic if the difference between consecutive elements is the same.
    • For example, [1, 2, 3] has a common difference of 1.
  2. Dynamic Programming Insight:
    • If nums[i-2], nums[i-1], and nums[i] form an arithmetic sequence, then extending the subarray ending at nums[i-1] to include nums[i] will also be arithmetic.
    • Let dp[i] represent the number of arithmetic slices ending at index i. If the condition is satisfied, dp[i] = dp[i-1] + 1, otherwise dp[i] = 0.
  3. Count Total Arithmetic Slices:
    • The total number of arithmetic slices is the sum of all values in dp.
  4. Optimization:
    • Instead of maintaining an entire dp array, we can use a single variable current to store the value of dp[i] and accumulate the result in a separate variable.
Python
class Solution:
    def numberOfArithmeticSlices(self, nums: List[int]) -> int:
        # Edge case: If there are fewer than 3 elements, no arithmetic slices exist
        if len(nums) < 3:
            return 0
        
        # Initialize variables
        current = 0  # Number of arithmetic slices ending at the current index
        total = 0    # Total count of arithmetic slices
        
        # Iterate through the array starting from the third element
        for i in range(2, len(nums)):
            # Check if the current subarray forms an arithmetic sequence
            if nums[i] - nums[i-1] == nums[i-1] - nums[i-2]:
                # Update the current count of slices
                current += 1
                # Add the current count to the total
                total += current
            else:
                # Reset current count if no arithmetic sequence continues
                current = 0
        
        return total

Explanation of the Code

  1. Edge Case:
    • If the array has fewer than three elements, return 0 since no arithmetic slices can exist.
  2. Iterative Check:
    • Start from the third element (i = 2) and check if the current three-element subarray is arithmetic.
  3. Dynamic Programming Update:
    • If the condition nums[i] - nums[i-1] == nums[i-1] - nums[i-2] is true:
      • Increment current by 1, as the current subarray extends previous slices.
      • Add current to total to account for the new arithmetic slices.
    • If the condition is false, reset current to 0.
  4. Return Result:
    • The variable total accumulates the total number of arithmetic slices and is returned as the result.

Solution in C++

C++
class Solution {
public:
    int numberOfArithmeticSlices(vector<int>& nums) {
        // If the size of nums is less than 3, no arithmetic subarray is possible
        if (nums.size() < 3) return 0;
        
        int count = 0; // To store the total number of arithmetic subarrays
        int currentCount = 0; // To keep track of consecutive arithmetic slices

        // Loop through the array starting from the second element
        for (int i = 2; i < nums.size(); ++i) {
            // Check if the current triplet forms an arithmetic sequence
            if (nums[i] - nums[i - 1] == nums[i - 1] - nums[i - 2]) {
                // Extend the current arithmetic subarray
                ++currentCount;

                // Add the count of new arithmetic subarrays formed by extending
                count += currentCount;
            } else {
                // Reset currentCount if the sequence is broken
                currentCount = 0;
            }
        }
        
        return count; // Return the total count of arithmetic subarrays
    }
};

Solution in Javascript

JavaScript
var numberOfArithmeticSlices = function(nums) {
    // Initialize the count of arithmetic subarrays
    let count = 0;
    // This variable will track the current streak of arithmetic slices
    let currentStreak = 0;

    // Iterate through the array starting from the second index
    // since we need at least three elements to form an arithmetic slice
    for (let i = 2; i < nums.length; i++) {
        // Check if the current triplet forms an arithmetic progression
        // by comparing the difference between consecutive elements
        if (nums[i] - nums[i - 1] === nums[i - 1] - nums[i - 2]) {
            // If the current triplet is part of an arithmetic progression,
            // increment the current streak counter
            currentStreak++;

            // Add the current streak count to the total count
            // as all subarrays ending at the current index
            // and having a length >= 3 are valid
            count += currentStreak;
        } else {
            // If the current triplet is not part of an arithmetic progression,
            // reset the streak counter
            currentStreak = 0;
        }
    }

    // Return the total count of arithmetic subarrays
    return count;
};

Solution in Java

Java
class Solution {
    public int numberOfArithmeticSlices(int[] nums) {
        // If the array has less than 3 elements, there can be no arithmetic slices
        if (nums.length < 3) {
            return 0;
        }

        // Variable to keep track of the total count of arithmetic subarrays
        int totalCount = 0;
        
        // Variable to track the length of the current arithmetic subarray streak
        int currentStreak = 0;

        // Iterate through the array starting from the second element
        for (int i = 2; i < nums.length; i++) {
            // Check if the current element continues the arithmetic sequence
            if (nums[i] - nums[i - 1] == nums[i - 1] - nums[i - 2]) {
                // If it does, increase the streak
                currentStreak++;

                // Add the streak length to the total count
                totalCount += currentStreak;
            } else {
                // If the sequence is broken, reset the streak
                currentStreak = 0;
            }
        }

        // Return the total count of arithmetic subarrays
        return totalCount;
    }
}

Subscribe
Notify of

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

Popular