Skip to content

Commit 093e8c8

Browse files
authored
Create arithmetic-slices.py
1 parent 80e16cf commit 093e8c8

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

Diff for: Python/arithmetic-slices.py

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# Time: O(n)
2+
# Space: O(1)
3+
4+
# A sequence of number is called arithmetic if it consists of at least three elements
5+
# and if the difference between any two consecutive elements is the same.
6+
#
7+
# For example, these are arithmetic sequence:
8+
#
9+
# 1, 3, 5, 7, 9
10+
# 7, 7, 7, 7
11+
# 3, -1, -5, -9
12+
# The following sequence is not arithmetic.
13+
#
14+
# 1, 1, 2, 5, 7
15+
#
16+
# A zero-indexed array A consisting of N numbers is given. A slice of that array is any pair
17+
# of integers (P, Q) such that 0 <= P < Q < N.
18+
#
19+
# A slice (P, Q) of array A is called arithmetic if the sequence:
20+
# A[P], A[p + 1], ..., A[Q - 1], A[Q] is arithmetic. In particular, this means that P + 1 < Q.
21+
#
22+
# The function should return the number of arithmetic slices in the array A.
23+
#
24+
# Example:
25+
#
26+
# A = [1, 2, 3, 4]
27+
#
28+
# return: 3, for 3 arithmetic slices in A: [1, 2, 3], [2, 3, 4] and [1, 2, 3, 4] itself.
29+
30+
class Solution(object):
31+
def numberOfArithmeticSlices(self, A):
32+
"""
33+
:type A: List[int]
34+
:rtype: int
35+
"""
36+
res, i = 0, 0
37+
while i+2 < len(A):
38+
start = i
39+
while i+2 < len(A) and A[i+2] + A[i] == 2*A[i+1]:
40+
res += i - start + 1
41+
i += 1
42+
i += 1
43+
44+
return res

0 commit comments

Comments
 (0)