LeetCode 2816: Double a Number Represented as a Linked List Solution

Master LeetCode problem 2816 (Double a Number Represented as a Linked List), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2816. Double a Number Represented as a Linked List

Problem Explanation

Explanation:

To double a number represented as a linked list, we can traverse the linked list from right to left, similar to how we perform addition manually. We start from the least significant digit and move towards the most significant digit, doubling each digit and updating it in the linked list. If a digit becomes greater than 9 after doubling, we propagate the carry to the next digit.

Algorithm:

  1. Initialize a variable carry to 0.
  2. Traverse the linked list from right to left.
  3. For each node:
    • Double the current node value and add the carry.
    • Update the node value to the remainder of the result divided by 10.
    • Update the carry to the result divided by 10.
  4. If there is a carry remaining after traversing all nodes, create a new node with the carry value and append it to the end of the linked list.
  5. Return the head of the updated linked list.

Time Complexity:

The time complexity of this algorithm is O(n), where n is the number of nodes in the linked list.

Space Complexity:

The space complexity is O(1) as we are not using any extra space apart from a constant number of variables.

:

Solution Code

class Solution {
    public ListNode doubleNumber(ListNode head) {
        ListNode current = head;
        int carry = 0;

        while (current != null) {
            int doubledValue = current.val * 2 + carry;
            current.val = doubledValue % 10;
            carry = doubledValue / 10;
            if (current.next == null && carry > 0) {
                current.next = new ListNode(carry);
                break;
            }
            current = current.next;
        }

        return head;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2816 (Double a Number Represented as a Linked List)?

This page provides optimized solutions for LeetCode problem 2816 (Double a Number Represented as a Linked List) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2816 (Double a Number Represented as a Linked List)?

The time complexity for LeetCode 2816 (Double a Number Represented as a Linked List) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2816 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2816 in Java, C++, or Python.

Back to LeetCode Solutions