LeetCode 1634: Add Two Polynomials Represented as Linked Lists
LeetCode 1634 Solution Explanation
Explanation
To add two polynomials represented as linked lists, we can traverse both linked lists simultaneously, adding the coefficients of corresponding terms and creating a new linked list to store the result. We will merge terms with the same power and remove any terms with a coefficient of 0.
Algorithm:
- Initialize three pointers,
ptr1
andptr2
to the heads of the two input linked lists, anddummyHead
to the head of the result linked list. - Traverse both input linked lists simultaneously.
- While both lists have nodes remaining:
- If the powers of the current nodes are equal, add the coefficients and create a new node in the result list with the sum.
- If one list has a higher power, copy the node to the result list.
- Attach any remaining nodes from both input lists to the result list.
- Return the head of the result linked list.
Time Complexity: O(max(m, n)), where m and n are the number of terms in the input polynomials. Space Complexity: O(max(m, n)) for the result linked list.
LeetCode 1634 Solutions in Java, C++, Python
class ListNode {
int coefficient;
int power;
ListNode next;
public ListNode(int coefficient, int power) {
this.coefficient = coefficient;
this.power = power;
}
}
public ListNode addTwoPolynomials(ListNode poly1, ListNode poly2) {
ListNode dummyHead = new ListNode(0, 0);
ListNode current = dummyHead;
while (poly1 != null && poly2 != null) {
if (poly1.power == poly2.power) {
int sum = poly1.coefficient + poly2.coefficient;
if (sum != 0) {
current.next = new ListNode(sum, poly1.power);
current = current.next;
}
poly1 = poly1.next;
poly2 = poly2.next;
} else if (poly1.power > poly2.power) {
current.next = new ListNode(poly1.coefficient, poly1.power);
current = current.next;
poly1 = poly1.next;
} else {
current.next = new ListNode(poly2.coefficient, poly2.power);
current = current.next;
poly2 = poly2.next;
}
}
while (poly1 != null) {
current.next = new ListNode(poly1.coefficient, poly1.power);
current = current.next;
poly1 = poly1.next;
}
while (poly2 != null) {
current.next = new ListNode(poly2.coefficient, poly2.power);
current = current.next;
poly2 = poly2.next;
}
return dummyHead.next;
}
Interactive Code Editor for LeetCode 1634
Improve Your LeetCode 1634 Solution
Use the editor below to refine the provided solution for LeetCode 1634. Select a programming language and try the following:
- Add import statements if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.
Loading editor...