Losing head/tail while rewiring
Wrong move: Pointer updates overwrite references before they are saved.
Usually fails on: List becomes disconnected mid-operation.
Fix: Store next pointers first and use a dummy head for safer joins.
Move from brute-force thinking to an efficient approach using linked list strategy.
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 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 = [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). - We insert the greatest common divisor of 18 and 6 = 6 between the 1st and the 2nd nodes. - We insert the greatest common divisor of 6 and 10 = 2 between the 2nd and the 3rd nodes. - We insert the greatest common divisor of 10 and 3 = 1 between the 3rd and the 4th nodes. There are no more adjacent nodes, so we return the linked list.
Example 2:
Input: head = [7] Output: [7] Explanation: The 1st diagram denotes the initial linked list and the 2nd diagram denotes the linked list after inserting the new nodes. There are no pairs of adjacent nodes, so we return the initial linked list.
Constraints:
[1, 5000].1 <= Node.val <= 1000Problem summary: 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 linked list after insertion. The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Linked List · Math
[18,6,10,3]
[7]
reverse-linked-list)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2807: Insert Greatest Common Divisors in Linked List
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode insertGreatestCommonDivisors(ListNode head) {
for (ListNode pre = head, cur = head.next; cur != null; cur = cur.next) {
int x = gcd(pre.val, cur.val);
pre.next = new ListNode(x, cur);
pre = cur;
}
return head;
}
private int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
}
// Accepted solution for LeetCode #2807: Insert Greatest Common Divisors in Linked List
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func insertGreatestCommonDivisors(head *ListNode) *ListNode {
for pre, cur := head, head.Next; cur != nil; cur = cur.Next {
x := gcd(pre.Val, cur.Val)
pre.Next = &ListNode{x, cur}
pre = cur
}
return head
}
func gcd(a, b int) int {
if b == 0 {
return a
}
return gcd(b, a%b)
}
# Accepted solution for LeetCode #2807: Insert Greatest Common Divisors in Linked 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]:
pre, cur = head, head.next
while cur:
x = gcd(pre.val, cur.val)
pre.next = ListNode(x, cur)
pre, cur = cur, cur.next
return head
// Accepted solution for LeetCode #2807: Insert Greatest Common Divisors in Linked List
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #2807: Insert Greatest Common Divisors in Linked List
// /**
// * Definition for singly-linked list.
// * public class ListNode {
// * int val;
// * ListNode next;
// * ListNode() {}
// * ListNode(int val) { this.val = val; }
// * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
// * }
// */
// class Solution {
// public ListNode insertGreatestCommonDivisors(ListNode head) {
// for (ListNode pre = head, cur = head.next; cur != null; cur = cur.next) {
// int x = gcd(pre.val, cur.val);
// pre.next = new ListNode(x, cur);
// pre = cur;
// }
// return head;
// }
//
// private int gcd(int a, int b) {
// if (b == 0) {
// return a;
// }
// return gcd(b, a % b);
// }
// }
// Accepted solution for LeetCode #2807: Insert Greatest Common Divisors in Linked List
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
function insertGreatestCommonDivisors(head: ListNode | null): ListNode | null {
for (let pre = head, cur = head.next; cur; cur = cur.next) {
const x = gcd(pre.val, cur.val);
pre.next = new ListNode(x, cur);
pre = cur;
}
return head;
}
function gcd(a: number, b: number): number {
if (b === 0) {
return a;
}
return gcd(b, a % b);
}
Use this to step through a reusable interview workflow for this problem.
Copy all n nodes into an array (O(n) time and space), then use array indexing for random access. Operations like reversal or middle-finding become trivial with indices, but the O(n) extra space defeats the purpose of using a linked list.
Most linked list operations traverse the list once (O(n)) and re-wire pointers in-place (O(1) extra space). The brute force often copies nodes to an array to enable random access, costing O(n) space. In-place pointer manipulation eliminates that.
Review these before coding to avoid predictable interview regressions.
Wrong move: Pointer updates overwrite references before they are saved.
Usually fails on: List becomes disconnected mid-operation.
Fix: Store next pointers first and use a dummy head for safer joins.
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.