Skip to content

2807. Insert Greatest Common Divisors in Linked List 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
 public:
  ListNode* insertGreatestCommonDivisors(ListNode* head) {
    for (ListNode* curr = head; curr->next != nullptr;) {
      ListNode* inserted =
          new ListNode(__gcd(curr->val, curr->next->val), curr->next);
      curr->next = inserted;
      curr = inserted->next;
    }
    return head;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public ListNode insertGreatestCommonDivisors(ListNode head) {
    for (ListNode curr = head; curr.next != null;) {
      ListNode inserted = new ListNode(gcd(curr.val, curr.next.val), curr.next);
      curr.next = inserted;
      curr = inserted.next;
    }
    return head;
  }

  private int gcd(int a, int b) {
    return b == 0 ? a : gcd(b, a % b);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def insertGreatestCommonDivisors(
      self, head: ListNode | None
  ) -> ListNode | None:
    curr = head
    while curr.next:
      inserted = ListNode(math.gcd(curr.val, curr.next.val), curr.next)
      curr.next = inserted
      curr = inserted.next
    return head