Double a Number Represented as a Linked List

Updated on 30 May, 2025
Double a Number Represented as a Linked List header image

Problem Statement

The task entails working with a linked list, where each node of the list represents a single digit of a non-negative integer. This integer is arranged such that the head of the list corresponds to the most significant digit and the last node to the least significant one. Importantly, these integers do not contain any leading zeroes, except in the special case where the number itself is zero. Your job is to double this represented integer and then return the linked list representation of the resulting doubled value. The main challenge is to perform the arithmetic operation directly on the linked list format without converting it into a different data format for manipulation.

Examples

Example 1

Input:

head = [1,8,9]

Output:

[3,7,8]

Explanation:

The figure above corresponds to the given linked list which represents the number 189. Hence, the returned linked list represents the number 189 * 2 = 378.

Example 2

Input:

head = [9,9,9]

Output:

[1,9,9,8]

Explanation:

The figure above corresponds to the given linked list which represents the number 999. Hence, the returned linked list reprersents the number 999 * 2 = 1998.

Constraints

  • The number of nodes in the list is in the range [1, 104]
  • 0 <= Node.val <= 9
  • The input is generated such that the list represents a number that does not have leading zeros, except the number 0 itself.

Approach and Intuition

Understanding the Problem:

  • We're given a linked list where each node represents a single digit of a non-negative integer.
  • There are no leading zeros in the number represented by the list, except if the number is 0.

Steps to Solve the Problem:

  1. Traverse the linked list to extract the number it represents.
  2. Double the extracted number.
  3. Convert the resulting number back to the linked list format.

Detailed Breakdown:

  1. Extract Number:

    • Initialize an integer (say num) to zero.
    • Traverse each node of the linked list from head to tail.
    • With each node, multiply num by 10 and add the current node's value.
  2. Double The Number:

    • Simply multiply the extracted number num by 2.
  3. Formulate Output Linked List:

    • Convert the resulting product back into a linked list.
    • If the result is zero, simply create a single node with value 0.
    • For non-zero results, continuously divide the number by 10 to fetch digits and form new nodes. Ensure the order of digits is maintained as in the original linked list.

Considerations:

  • Overflow: Directly working with linked list might help avoid overflow issues that could arise while dealing with large integers, but in Python, integers are arbitrary-precision so it doesn't pose a practical problem.
  • Edge Case: Single-node lists or lists that result in a number that needs to accommodate an extra node when doubled e.g., 999 becoming 1998.
  • Complexity: This approach ensures a linear traversal of the linked list, making the implementation efficient with regard to the constraints provided.

Solutions

  • C++
  • Java
  • Python
cpp
class Solution {
public:
    ListNode* processList(ListNode* root) {
        // If the initial node value exceeds 4, prepend a new node
        if (root->val > 4) {
            root = new ListNode(0, root);
        }
        
        // Iterate over the list nodes
        for (ListNode* curr = root; curr != nullptr; curr = curr->next) {
            // Double the node's value and keep the last digit
            curr->val = (curr->val * 2) % 10;
            
            // Check next node for value adjustments based on conditions
            if (curr->next != nullptr && curr->next->val > 4) {
                curr->val++;
            }
        }
        
        return root;
    }
};

In this solution, you tackle the problem of doubling the value of each node in a singly linked list, representing each digit of a number. Importantly, the operation adheres to the constraint where the linked list can undergo transformations like node addition if the conditions demand it.

  • The process begins by inspecting the head of the list.

  • If the value at the head exceeds 4, a new node with a value of 0 is prepended. This adjustment is essential for preserving the linked list structure during subsequent operations that might lead to an increase in the node count.

  • The core operation occurs within a loop that traverses each node starting from the modified root:

    • Each node's value is doubled, and the result is then adjusted to store only the last digit by utilizing the modulus operator (% 10).
    • Post the doubling, the solution must account for potential carry by examining the next node in advance. Specifically, if the next node's value is more than 4, it necessitates incrementing the current node's value by 1 to handle the carry from the doubling operation correctly.
  • This process iterates until all nodes in the list have been appropriately adjusted.

The essence of the solution is its efficient use of a single traversal to manage value updates and possible structure changes in the list due to carrying over magnitudes beyond a single digit, thereby ensuring the delivery of a modified list that accurately represents the doubled value.

java
public class Solution {
    public ListNode multiplyValues(ListNode head) {
        if (head.val > 4) {
            head = new ListNode(0, head);
        }

        ListNode temp = head;
        while (temp != null) {
            temp.val = (temp.val * 2) % 10;
            if (temp.next != null && temp.next.val > 4) {
                temp.val += 1;
            }
            temp = temp.next;
        }

        return head;
    }
}

This Java-based solution involves a method to double the numeric values in a linked list where each node corresponds to a single digit of a number. The method, multiplyValues, is designed to take a ListNode representing the head of the linked list as a parameter, and returns a modified list where each digit has been doubled, considering digit carry over for values over 4 (similar to a multiply by 2 operation).

  • The method starts by checking if the value of the head node exceeds 4. If it does, a new node with value 0 is prefixed to the head to handle any potential carry in the most significant digit during the multiplication process.
  • Initialize a temporary variable, temp, to traverse the linked list starting from the head.
  • Iterate through the linked list using a while loop:
    • Each node's value is doubled and taken modulo 10 to ensure it remains a single digit.
    • For nodes in linked list except the last one, check the next node's value. If it is greater than 4, add 1 to the current node's value to account for the carry over from the following node after its multiplication.
    • Continue to the next node.
  • Once all nodes have been appropriately modified, the modified head of the list is returned. This head will reflect the new set of values that are double those of the original list, adjusted for single-digit constraints and correctly handling carry through nodes.

This implementation ensures each node is processed in a forward manner, effectively simulating the multiplication of each digit by 2 while handling carries, following principles used in elementary base-ten arithmetic operations but applied within linked list data structures.

python
class Solution:
    def multiplyValues(self, first: ListNode) -> ListNode:
        if first.val > 4:
            first = ListNode(0, first)

        current = first
        while current:
            current.val = (current.val * 2) % 10
            if current.next and current.next.val > 4:
                current.val += 1
            current = current.next

        return first

In the given Python code, you receive a function multiplyValues that takes a linked list, representing a number, and doubles its value. This solution manipulates the linked list in such a way that each node's value is correctly adjusted to represent the number after it is doubled.

  • The function first checks if the most significant digit (first.val) is greater than 4. If so, a new node with value 0 is added at the beginning to handle any overflow that occurs when the number is doubled.
  • It iterates through each node in the linked list (current), doubling the current node's value and ensuring that the result remains a single digit by taking modulo 10.
  • If the next node's value will cause an overflow (values greater than 4), it adjusts the current node's value by adding 1 to carry over the overflow.
  • The process continues until the end of the list is reached.

By following these steps, the function effectively and efficiently doubles any number represented as a linked list and ensures the linked list still correctly represents a number after the operation.

Comments

No comments yet.