Skip to content

Commit dab1c52

Browse files
committed
Update arithmetic_slices.py
2 parents eff3196 + 61d5edd commit dab1c52

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
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+
17+
class ArithmeticSlices:
18+
def numberofarithmeticslices(self, nums):
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+
<<<<<<< HEAD
56+
So at each step,
57+
we are looking at a triplet ending at index `i`.
58+
=======
59+
So at each step,
60+
we’re looking at a triplet ending at index `i`.
61+
>>>>>>> ca34f0a649ef94c8b778a4babe040fcaa143a56e
62+
"""
63+
64+
return total
65+
66+
67+
"""
68+
test_cases = [
69+
# Basic cases
70+
([1, 2, 3, 4], 3), # [1,2,3], [2,3,4], [1,2,3,4]
71+
([1, 3, 5, 7, 9], 6), # all diffs = 2;
72+
total slices = 6
73+
74+
# Edge cases
75+
([1, 2], 0), # less than 3 elements → 0
76+
([1, 1, 1], 1), # [1,1,1] itself is arithmetic
77+
([1], 0), # single element
78+
([], 0), # empty array
79+
]
80+
"""

0 commit comments

Comments
 (0)