Arithmetic Slices

An integer array is called arithmetic if it has at least three elements and 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. Given an integer array `nums`, return the number of arithmetic subarrays of `nums`. A subarray is a contiguous part of an array.

30:00

Arithmetic Slices
medium
Free written solution
Topics
Companies

An integer array is called arithmetic if it has at least three elements and 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.

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

A subarray is a contiguous part of an array.

Example 1:
Input: {"nums":[1,2,3,4]}
Output: 3
Constraints:
  • 1≤nums.length≤50001 \leq \text{nums.length} \leq 5000

  • −1000≤nums[i]≤1000-1000 \leq \text{nums}[i] \leq 1000

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[1,2,3,4]}

A slice is arithmetic when every step between neighbours is equal, so the chips under the cells show each step.

steps between neighbours

1
2
3
4
+1
+1
+1

0

1

2

3

curr (end at i)

-

total

0

Variables
VariableValue
n4
DepthFunction Call
Stack empty
0/6