![]() |
VOOZH | about |
Given two polynomials represented by two arrays, write a function that adds given two polynomials.
Example:
Input: A[] = {5, 0, 10, 6}
B[] = {1, 2, 4}
Output: sum[] = {6, 2, 14, 6}
The first input array represents "5 + 0x^1 + 10x^2 + 6x^3"
The second array represents "1 + 2x^1 + 4x^2"
And Output is "6 + 2x^1 + 14x^2 + 6x^3"
We strongly recommend minimizing your browser and try this yourself first.
Addition is simpler than multiplication of polynomials. We initialize the result as one of the two polynomials, then we traverse the other polynomial and add all terms to the result.
add(A[0..m-1], B[0..n01]) 1) Create a sum array sum[] of size equal to maximum of 'm' and 'n' 2) Copy A[] to sum[]. 3) Traverse array B[] and do following for every element B[i] sum[i] = sum[i] + B[i] 4) Return sum[].
The following is the implementation of the above algorithm.
Output:
First polynomial is 5 + 0x^1 + 10x^2 + 6x^3 Second polynomial is 1 + 2x^1 + 4x^2 Sum polynomial is 6 + 2x^1 + 14x^2 + 6x^3
Time complexity: O(m+n) where m and n are orders of two given polynomials.
Auxiliary Space: O(max(m, n))
Linked List 5x^2 4x^1 Linked List 6x^2 4x^1 Addition: 11x^2 8x^1
Time Complexity: O(m + n) where m and n are number of nodes in first and second lists respectively.
Auxiliary Space: O(m + n) where m and n are number of nodes in first and second lists respectively due to recursion.
Approach
This implementation takes two arguments p1 and p2, which are lists representing the coefficients of two polynomials. The function returns a new list representing the sum of the two input polynomials.
The function first checks the lengths of the two input lists and pads the shorter list with zeros so that both lists have the same length. We then use the zip function to create pairs of corresponding coefficients from the two input lists, and the sum function to add the pairs together. The resulting sum is appended to a new list, which is returned at the end.
[2, 0, 5, 8, 8]
time complexity: O(n), where n is the max of length of two polynomials
space complexity: O(n). where n is the max of length of two polynomials