#2816
Double a Number Represented as a Linked List
MediumLinked ListMathStackStackTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach involves traversing the linked list from the least significant digit to the most significant digit, doubling each value and managing carry-over directly. This avoids the overhead of converting to and from a number.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a carry variable to 0.
- 2Step 2: Traverse the linked list from the end to the start, doubling each node's value and adding the carry.
- 3Step 3: If the doubled value is greater than 9, set the current node's value to (doubled value % 10) and update the carry.
- 4Step 4: If there's a carry left after processing all nodes, create a new node for the carry.
solution.py22 lines
1class ListNode:
2 def __init__(self, val=0, next=None):
3 self.val = val
4 self.next = next
5
6def doubleLinkedList(head):
7 carry = 0
8 current = head
9 stack = []
10 while current:
11 stack.append(current)
12 current = current.next
13 while stack:
14 node = stack.pop()
15 doubled_value = node.val * 2 + carry
16 node.val = doubled_value % 10
17 carry = doubled_value // 10
18 if carry:
19 new_head = ListNode(carry)
20 new_head.next = head
21 return new_head
22 return headℹ
Complexity note: The time complexity is O(n) because we traverse the linked list once to push nodes onto the stack and then again to process them. The space complexity is O(n) due to the stack storing the nodes.
- 1Understanding how to manage carry-over is crucial when dealing with digit manipulation.
- 2Using a stack allows us to reverse the order of processing, which is essential for linked lists representing numbers.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.