Math Fundamentals18 sections · 814 units
Open in Course

Arithmetic Slices - Implementation

In pseudocode

Here's the solution:


function numberOfArithmeticSlices(nums)
    n := length of nums
    if n < 3 then
        return 0
    count := 0
    length := 2  // current arithmetic sequence length
    for i from 2 to n - 1
        if nums[i] - nums[i - 1] = nums[i - 1] - nums[i - 2] then
            length := length + 1
        else
            if length  3 then
                k := length - 2
                count := count + (k × (k + 1)) / 2
            length := 2
    if length  3 then
        k := length - 2
        count := count + (k × (k + 1)) / 2
    return count

The formula (k×(k+1))/2(k \times (k + 1)) / 2 counts slices for a sequence of length length=k+2length = k + 2. This runs in O(n)O(n) time.