Problem
Table: Terms
|
|
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 = 1
andfactor = 3
, the term will be"+3X"
.
- For example, if
- If the power is
0
, add neither"X"
nor"^<pow>"
.- For example, if
power = 0
andfactor = -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.
Examples
Example 1:
|
|
Example 2:
|
|
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
Method 1 – String Construction with Sorting
Intuition
We need to construct the equation string by sorting the terms by power in descending order and formatting each term according to the rules. This is a direct string manipulation problem with careful attention to formatting.
Approach
- Select all terms from the Terms table.
- Sort the terms by
power
in descending order. - For each term:
- If
power
is 0, append the factor as a signed integer. - If
power
is 1, append the factor followed by ‘X’ (no power). - Otherwise, append the factor followed by ‘X^’ and the power.
- If
- Concatenate all terms into a single string.
- Append ‘=0’ at the end.
- Return the result as the equation column.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n log Nn
for sortingn
items - 🧺 Space complexity:
O(n)
for the result string