Math Fundamentals18 sections · 814 units
Open in Course

Arithmetic Slices - Algorithm

Track consecutive arithmetic elements

Scan the array and track the length of the current arithmetic sequence. When the difference changes, count the slices from the previous sequence and reset.

For each position, check if nums[i]nums[i1]nums[i] - nums[i-1] equals the previous difference. If yes, increment the sequence length. If no, use the formula to count slices and start a new sequence.

This takes O(n)O(n) time with O(1)O(1) space. The summation formula eliminates nested loops.