Last Updated: 27 Aug, 2020

Evaluate the Polynomial

Easy
Asked in companies
AckoMicrosoftIBM

Problem statement

You are given two arrays of coefficients and degrees of a polynomial expression. You need to simplify the polynomial in general form by evaluating and simplifying the expression.

For Example:
If the given polynomial equation is “5x ^ 3 + 2x ^ 3 + 6x ^ 4 + 2”. There are two terms of exponent or degree 3 and they are 5x ^ 3 and 2x ^ 3. Both these terms will get added and form 7x ^ 3, so the given polynomial will be simplified as 7x ^ 3 + 6x ^ 4 + 2. Now by arranging the expression in the decreasing order of the degrees, we will have 6x ^ 4 + 7x ^ 3 + 2 and hence the result.
Input Format :
The first line of input contains a single integer 'T', representing the number of test cases/queries to be run. 
Then the test cases follow.

The first line of each test case contains a positive integer 'N' which represents the number of terms in the polynomial.

The second line of each test case contains 'N' integers denoting the coefficients of the polynomial.

The third line of each test case contains 'N' integers denoting the degree of the polynomial.
Output Format :
For each test case, print a single line containing two space-separated integers denoting the coefficient and degree of the term respectively.
The result will be printed in descending order of the degrees.

The output for each test case will be printed in a new line.
Note :
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints :
0 <= T <= 10
1 <= N <= 10 ^ 5
-10 ^ 5 <= coefficient <= 10 ^ 5
0 <= degree <= 10 ^ 5

Time Limit: 1 sec.

Approaches

01 Approach

  1. Initialise a map which will store the coefficients as value and exponent as key.
  2. For every term in the polynomial, update the coefficients in the map.
  3. If the coefficient becomes zero then remove the entry from the map.
  4. Sort the key values in descending order.
  5. Initialize the answer array.
  6. Add all non-zero coefficients in the array and return it.