Build the Equation Problem
#2118
Description
LeetCode Problem 2118.
Table: Terms
+-------------+------+
| Column Name | Type |
+-------------+------+
| power | int |
| factor | int |
+-------------+------+
power is the column with unique values for this table.
Each row of this table contains information about one term of the equation.
power is an integer in the range [0, 100].
factor is an integer in the range [-100, 100] and cannot be zero.
You have a very powerful program that can solve any equation of one variable in the world. The equation passed to the program must be formatted as follows:
- The left-hand side (LHS) should contain all the terms.
- The right-hand side (RHS) should be zero.
- Each term of the LHS should follow the format
"<sign><fact>X^<pow>"where:<sign>is either"+"or"-".<fact>is the absolute value of thefactor.<pow>is the value of thepower.
- If the power is
1, do not add"^<pow>".- For example, if
power = 1andfactor = 3, the term will be"+3X".
- For example, if
- If the power is
0, add neither"X"nor"^<pow>".- For example, if
power = 0andfactor = -3, the term will be"-3".
- For example, if
- The powers in the LHS should be sorted in descending order.
Write a solution to build the equation.
The result format is in the following example.
Example 1:
Input:
Terms table:
+-------+--------+
| power | factor |
+-------+--------+
| 2 | 1 |
| 1 | -4 |
| 0 | 2 |
+-------+--------+
Output:
+--------------+
| equation |
+--------------+
| +1X^2-4X+2=0 |
+--------------+
Example 2:
Input:
Terms table:
+-------+--------+
| power | factor |
+-------+--------+
| 4 | -4 |
| 2 | 1 |
| 1 | -1 |
+-------+--------+
Output:
+-----------------+
| equation |
+-----------------+
| -4X^4+1X^2-1X=0 |
+-----------------+
Follow up: What will be changed in your solution if the power is not a primary key but each power should be unique in the answer?
Solution
Approach: Format each term and concatenate
Format each term on its own, then glue the terms together in descending power order.
- The sign is
+for a positive factor and-for a negative one (a factor is never zero). The number printed is always the absolute value. - Power 0 prints only the number, power 1 prints
X, and higher powers printX^power. GROUP_CONCAT(... ORDER BY power DESC SEPARATOR '')joins the terms in the right order, and=0is appended at the end.
The sign is written explicitly and the number is taken with ABS, so a negative factor is not printed with a second sign.
SELECT CONCAT(
GROUP_CONCAT(
CONCAT(IF(factor > 0, '+', '-'),
ABS(factor),
CASE power
WHEN 0 THEN ''
WHEN 1 THEN 'X'
ELSE CONCAT('X^', power)
END)
ORDER BY power DESC
SEPARATOR ''
),
'=0'
) AS equation
FROM Terms;