DSAPLL - Editorial

Problem Link - Link List- Polynomial Representation and Addition

Problem statement

You are given two polynomials, each represented using a linked list. Each node of the linked list contains two fields: ax^b

  • Coefficient (a): The coefficient of the polynomial term.

  • Exponent (b): The exponent of the variable in the term.

The program needs to perform the following operations on these polynomials:

  1. Addition: Add the two polynomials.

  2. Subtraction: Subtract the second polynomial from the first.

  3. Multiplication: Multiply the two polynomials.

Approach:

  1. Addition of Two Polynomials: Traverse both polynomials:

    • If one has a higher exponent, add that term to the result.

    • If exponents match, sum the coefficients.

    • If one polynomial has remaining terms, append them to the result.

  2. Subtraction of Two Polynomials: Similar to addition but subtract the coefficients of matching exponents.

  3. Multiplication of Two Polynomials:

    • Multiply each term of the first polynomial with every term of the second:

      • New term coefficient: product of coefficients.
      • New term exponent: sum of exponents.
    • Insert resulting terms into a new polynomial, combining like terms.

    • Traverse the linked list to print each term as ax^b.

Time Complexity:

  • Addition/Subtraction: O(n + m), where n and m are the number of terms in each polynomial.

  • Multiplication: O(n × m).

Space Complexity:

  • Addition/Subtraction: O(n + m).

  • Multiplication: O(n × m) (before combining like terms).