#2807

Insert Greatest Common Divisors in Linked List

Medium
Linked ListMathNumber TheoryLinked ListMathematical Operations
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach is similar to the brute force method but focuses on efficiently inserting nodes while traversing the list. We maintain a single pointer and adjust the links as we go, ensuring we only traverse the list once.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a pointer to the head of the linked list.
  2. 2Step 2: While the pointer has a next node, calculate the GCD of the current node and the next node.
  3. 3Step 3: Create a new node with the GCD value and insert it between the current node and the next node.
  4. 4Step 4: Move the pointer to the next node (skipping the newly inserted node).
  5. 5Step 5: Repeat until the end of the list is reached.
solution.py14 lines
1import math
2class ListNode:
3    def __init__(self, val=0, next=None):
4        self.val = val
5        self.next = next
6
7def insertGCD(head):
8    current = head
9    while current and current.next:
10        gcd_value = math.gcd(current.val, current.next.val)
11        new_node = ListNode(gcd_value, current.next)
12        current.next = new_node
13        current = new_node.next
14    return head

Complexity note: The time complexity is O(n) because we only traverse the linked list once. The space complexity is O(1) as we are modifying the list in place without using any extra space.

  • 1Understanding GCD is crucial for this problem.
  • 2Linked list manipulation requires careful handling of pointers.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.