Insert Greatest Common Divisors in Linked List — LeetCode 2807 Python Solution
- Problem
- #2807
- Pattern
- Linked List
- Reading time
- 3 min
- Source
- leetcode.com
The problem
Given the head of a linked list head, in which each node contains an integer value. Between every pair of adjacent nodes, insert a new node with a value equal to the greatest common divisor of them.
Example
- Input
- head = [18,6,10,3]
- Output
- [18,6,6,2,10,1,3]
- Explanation
- The 1st diagram denotes the initial linked list and the 2nd diagram denotes the linked list after inserting the new nodes (nodes in blue are the inserted nodes).
Python solution
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def insertGreatestCommonDivisors(
self, head: Optional[ListNode]
) -> Optional[ListNode]:
pre, cur = head, head.next
while cur:
x = gcd(pre.val, cur.val)
pre.next = ListNode(x, cur)
pre, cur = cur, cur.next
return headComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log M), where n is the length of the linked list, and M is the maximum value of the nodes in the linked list |
| Space | O(1) auxiliary |
Pattern: Linked List
Rewire pointers in place, with a dummy head and a saved next to keep it safe. LeetCode 2807. Insert Greatest Common Divisors in Linked List is filed here because LeetCode tags it Linked List, which is the vocabulary this hub collects.
The linked list guide has the Python template for the pattern and the 75 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2807. Insert Greatest Common Divisors in Linked List?
- LeetCode 2807. Insert Greatest Common Divisors in Linked List is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2807. Insert Greatest Common Divisors in Linked List?
- The Python solution on this page runs in O(n \times \log M), where n is the length of the linked list, and M is the maximum value of the nodes in the linked list.
- What is the space complexity of LeetCode 2807. Insert Greatest Common Divisors in Linked List?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2807. Insert Greatest Common Divisors in Linked List cover?
- LeetCode 2807. Insert Greatest Common Divisors in Linked List is tagged Linked List, Math and Number Theory on LeetCode.