1+ """
2+ An integer array is called arithmetic if it
3+ consists of at least three elements and if
4+ the difference between any two consecutive
5+ elements is the same.
6+
7+ Given an integer array nums,
8+ return the number of
9+ arithmetic subarrays of nums.
10+
11+ A subarray is a contiguous
12+ subsequence of the array.
13+
14+ """
15+
16+ class ArithmeticSlices :
17+ def numberofarithmeticslices (self , nums ):
18+
19+ """
20+ This defines a class and a function.
21+ `nums` is input list of integers.
22+ """
23+ n = len (nums )
24+
25+ """
26+ We store the length of the
27+ array nums in variable n
28+ """
29+ if n < 3 :
30+ return 0
31+
32+ total = 0
33+ curr = 0
34+
35+ """
36+ An *arithmetic slice* must have **at least 3 numbers**.
37+
38+ So, if the array has fewer than 3 elements,
39+ no arithmetic slices are possible — immediately return `0`.
40+ """
41+
42+ for i in range (2 , n ):
43+ if nums [i ] - nums [i - 1 ] == nums [i - 1 ] - nums [i - 2 ]:
44+ curr += 1
45+ total += curr
46+ else :
47+ curr = 0
48+
49+ """
50+ We start iterating from index `2`
51+ because we need **three elements**
52+ (`nums[i-2], nums[i-1], nums[i]`)
53+ to check if they form an arithmetic pattern.
54+
55+ So at each step,
56+ we’re looking at a triplet ending at index `i`.
57+ """
58+
59+ return total
60+
61+ """
62+ test_cases = [
63+ # Basic cases
64+ ([1, 2, 3, 4], 3), # [1,2,3], [2,3,4], [1,2,3,4]
65+ ([1, 3, 5, 7, 9], 6), # all diffs = 2;
66+ total slices = 6
67+
68+ # Edge cases
69+ ([1, 2], 0), # less than 3 elements → 0
70+ ([1, 1, 1], 1), # [1,1,1] itself is arithmetic
71+ ([1], 0), # single element
72+ ([], 0), # empty array
73+ ]
74+ """
0 commit comments