Problem
Table: Elements
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| symbol | varchar |
| type | enum |
| electrons | int |
+-------------+---------+
symbol is the primary key (column with unique values) for this table.
Each row of this table contains information of one element.
type is an ENUM (category) of type ('Metal', 'Nonmetal', 'Noble')
- If type is Noble, electrons is 0.
- If type is Metal, electrons is the number of electrons that one atom of this element can give.
- If type is Nonmetal, electrons is the number of electrons that one atom of this element needs.
Two elements can form a bond if one of them is 'Metal'
and the other is
'Nonmetal'
.
Write a solution to find all the pairs of elements that can form a bond.
Return the result table in any order.
The result format is in the following example.
Examples
Example 1:
|
|
Solution
Method 1 – Self Join and Filtering
Intuition
A chemical bond can be formed between a metal and a nonmetal if the number of electrons given by the metal equals the number needed by the nonmetal. We can use a self join to pair metals and nonmetals and filter by their electron counts.
Approach
- Select all pairs of elements where one is a metal and the other is a nonmetal.
- Ensure the number of electrons given by the metal equals the number needed by the nonmetal.
- Output the metal and nonmetal symbol pairs.
- Order the result by metal symbol and nonmetal symbol.
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(m * n)
, wherem
is the number of metals andn
is the number of nonmetals, due to the join operation. - 🧺 Space complexity:
O(m * n)
for storing the join result.