algoadvance

The problem is to calculate the number of arithmetic slices in a given list of integers.

A sequence of numbers is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.

Given an array of integers nums, return the number of arithmetic subarrays of nums.

Example 1:

Input: nums = [1, 2, 3, 4]
Output: 3
Explanation: There are three arithmetic slices in input array: [1, 2, 3], [2, 3, 4], and [1, 2, 3, 4] itself.

Example 2:

Input: nums = [1]
Output: 0

Clarifying Questions

  1. Can the array have negative numbers?
    • Yes, the array can have negative numbers.
  2. What should be returned if the input array has fewer than three elements?
    • If the input array has fewer than three elements, the function should return 0 as no arithmetic slice can be formed.

Strategy

  1. Initialization: Start by initializing a variable current to keep track of the number of arithmetic slices ending at the current position and a variable total to keep the total count of arithmetic slices.
  2. Iterate through the array: Loop over the array starting from the third element.
  3. Check for Arithmetic Slice: For each element, check if the difference between consecutive elements is the same as the difference for the previous pair of elements.
  4. Update Count: If it forms an arithmetic slice, increment the current count and add it to the total.
  5. Reset Count: If it does not form an arithmetic slice, reset the current count to zero.
  6. Return Total: After the loop, return the total count.

Code

def numberOfArithmeticSlices(nums):
    if len(nums) < 3:
        return 0
    
    total, current = 0, 0
    
    for i in range(2, len(nums)):
        if nums[i] - nums[i - 1] == nums[i - 1] - nums[i - 2]:
            current += 1
            total += current
        else:
            current = 0
    
    return total

Time Complexity

This solution is efficient and meets the problem’s requirements by iterating over the list in linear time and using constant space.

Try our interview co-pilot at AlgoAdvance.com