2807. Insert Greatest Common Divisors in Linked List - Explanation
Description
You are 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.
Return the head of the linked list after insertion.
The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers.
Example 1:
Input: head = [12,3,4,6]
Output: [12,3,3,1,4,2,6]Example 2:
Input: head = [2,1]
Output: [2,1,1]Constraints:
1 <= The length of the list <= 5000.1 <= Node.val <= 1000
Topics
Prerequisites
Before attempting this problem, you should be comfortable with:
- Linked Lists - Understanding node structure, traversal, and inserting nodes between existing nodes
- GCD (Greatest Common Divisor) - Knowing the Euclidean algorithm for efficiently computing the GCD of two numbers
- Pointer Manipulation - Safely adjusting next pointers without losing references or creating infinite loops
1. Simulation
Intuition
The problem asks us to insert a new node between every pair of adjacent nodes, where the new node's value is the GCD of its neighbors. We traverse the list and for each pair of consecutive nodes, compute their gcd and create a new node with that value.
The Euclidean algorithm efficiently computes the gcd: repeatedly replace the larger number with the remainder of dividing the two numbers until one becomes zero. The other number is the gcd.
Since we're inserting nodes as we traverse, we need to be careful to advance the pointer past the newly inserted node to avoid processing it again.
Algorithm
- Start with
curpointing to the head of the list. - While
cur.nextexists:- Get the values of
curandcur.nextasn1andn2. - Compute their
gcdusing the Euclidean algorithm. - Create a new node with the
gcdvalue. - Insert it between
curandcur.nextby adjusting pointers. - Move
curtocur.next.nextto skip over the newly inserted node.
- Get the values of
- Return the head of the modified list.
# 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]:
def gcd(a, b):
while b > 0:
a, b = b, a % b
return a
cur = head
while cur.next:
n1, n2 = cur.val, cur.next.val
cur.next = ListNode(gcd(n1, n2), cur.next)
cur = cur.next.next
return headTime & Space Complexity
- Time complexity:
- Space complexity:
- space for the gcd ListNodes.
- extra space.
Where is the length of the given list, and and are two numbers passed to the function.
Common Pitfalls
Processing Newly Inserted Nodes
After inserting a GCD node between cur and cur.next, forgetting to skip over the newly inserted node causes an infinite loop. The pointer must advance by two positions (cur = cur.next.next) to move past both the inserted node and reach the next original node that needs processing.
Incorrect GCD Implementation
Implementing the Euclidean algorithm incorrectly by not handling the base case properly or swapping values in the wrong order. The algorithm should continue until one value becomes zero, and the order of operands in the modulo operation matters. Using a % b when a < b returns a, which is correct, but some implementations incorrectly assume a > b.
Off-by-One at List End
Attempting to access cur.next.val when cur.next is null causes a null pointer exception. The loop condition must be while cur.next (not while cur) to ensure there is always a valid pair of adjacent nodes to compute the GCD between.
Sign in to join the discussion