Skip to main content

Build the Equation - Solution & Explanation

HardPremiumFree on FleetCodeDatabase4 min read
Practice this problem

Problem Statement

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 the factor.
    • <pow> is the value of the power.
  • If the power is 1, do not add "^<pow>".
    • For example, if power = 1 and factor = 3, the term will be "+3X".
  • If the power is 0, add neither "X" nor "^<pow>".
    • For example, if power = 0 and factor = -3, the term will be "-3".
  • 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?

Approach Overview

Problem Overview: Each row represents a polynomial term with a coefficient (factor) and exponent (power). Your job is to convert these rows into a single formatted equation string such as 3x^2+2x-5, ordered by descending power and formatted according to algebra rules.

Approach 1: CASE Formatting + GROUP_CONCAT (O(n log n) time, O(n) space)

The clean SQL solution formats every term independently and then concatenates them into a single string. Use CASE expressions to convert each row into its textual representation: factor only when power = 0, factorx when power = 1, and factorx^power otherwise. Handle positive signs by prefixing '+' when the factor is positive so that intermediate terms concatenate correctly.

Once every row is converted into a formatted term, combine them using MySQL’s GROUP_CONCAT. Apply ORDER BY power DESC inside the aggregation so the highest power appears first, matching the standard polynomial format. Finally, remove a possible leading '+' from the final string with TRIM or SUBSTRING. The database scans all rows and performs a sort during aggregation, giving O(n log n) time and O(n) output space.

This approach relies entirely on SQL string manipulation and aggregation features, which is exactly what interviewers want to see in a database problem. The key insight is treating each polynomial term as a formatted string before aggregation rather than trying to build the equation incrementally.

Approach 2: Incremental Concatenation with Variables (O(n log n) time, O(n) space)

Another option uses MySQL user-defined variables to iteratively build the equation string. First sort rows by power DESC. Then iterate through the ordered rows while appending formatted terms to a variable using CONCAT. Each row still uses CASE logic to format the correct representation (x, x^power, or constant).

This method mimics procedural string building inside SQL. While it works, it is more verbose and less portable across SQL engines. Modern SQL solutions generally prefer aggregation functions like GROUP_CONCAT because they express the transformation declaratively and integrate naturally with SQL query patterns.

Recommended for interviews: The CASE + GROUP_CONCAT approach is the expected solution. It shows you understand SQL aggregation, conditional formatting, and ordering inside aggregation. A procedural variable approach demonstrates the same idea but is less idiomatic. Interviewers usually want to see strong string manipulation combined with SQL aggregation.

Solution

Code

MySQL

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
CASE + GROUP_CONCAT aggregationO(n log n)O(n)Best general SQL solution when building a formatted string from multiple rows
Procedural concatenation with variablesO(n log n)O(n)Useful when aggregation functions are unavailable or procedural SQL logic is preferred

Video Solution

Leetcode HARD 2118 - Build The Equation CONCAT vs GROUP_CONCAT : Explained by Everyday Data Science • Everyday Data Science • 430 views views

Frequently Asked Questions

Is Build the Equation easy or hard?
The problem is rated Hard because it requires careful string formatting rules combined with SQL aggregation and ordering. Handling signs, powers, and edge cases like power 0 or 1 correctly is where most mistakes occur.
Build the Equation Python/Java solution
The canonical solution is written in SQL because the problem belongs to the Database category. In application code like Python or Java, you would read the rows, sort them by power descending, format each term as a string, and join them together.
How to solve Build the Equation in O(n)?
If the data is already stored in descending power order or indexed appropriately, the aggregation step effectively becomes O(n). Each row is formatted using CASE and appended through GROUP_CONCAT without additional sorting.
What is the best approach for Build the Equation?
The most efficient approach uses SQL conditional formatting with CASE and aggregation using GROUP_CONCAT. Each row is converted into a formatted polynomial term, then all terms are concatenated in descending power order. This produces the final equation string in a single query.
Is Build the Equation asked at Google/Amazon/Meta?
Database string aggregation and formatting problems frequently appear in SQL interview rounds at companies like Amazon, Meta, and analytics-focused teams. The problem tests practical SQL skills such as conditional logic, ordering, and aggregation.
What data structure is used in Build the Equation?
The problem operates on relational database rows rather than traditional in-memory data structures. The main tools are SQL aggregation functions, conditional CASE expressions, and string concatenation to construct the polynomial equation.
What is the time complexity of Build the Equation?
The query processes all rows and sorts them by power before concatenation. Sorting dominates the cost, resulting in O(n log n) time complexity. The output string requires O(n) space because every term becomes part of the final equation.

Ready to solve this problem?

Practice Build the Equation with our built-in code editor and test cases.

Practice on FleetCode