Skip to content

Commit 0ffbc5f

Browse files
authored
Create insert-greatest-common-divisors-in-linked-list.py
1 parent 2da8962 commit 0ffbc5f

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Time: O(n)
2+
# Space: O(1)
3+
4+
# linked list
5+
class Solution(object):
6+
def insertGreatestCommonDivisors(self, head):
7+
"""
8+
:type head: Optional[ListNode]
9+
:rtype: Optional[ListNode]
10+
"""
11+
def gcd(a, b):
12+
while b:
13+
a, b = b, a%b
14+
return a
15+
16+
curr = head
17+
while curr.next:
18+
curr.next = ListNode(gcd(curr.val, curr.next.val), curr.next)
19+
curr = curr.next.next
20+
return head

0 commit comments

Comments
 (0)