Problem
Table: cities
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| state | varchar |
| city | varchar |
+-------------+---------+
(state, city) is the primary key (combination of columns with unique values) for this table.
Each row of this table contains the state name and the city name within that state.
Write a solution to find all the cities in each state and combine them into a single comma-separated string.
Return the result table ordered by state
and city
inascending order.
The result format is in the following example.
Example 1:
|
|
Solution
Method 1 – String Aggregation with GROUP_CONCAT / STRING_AGG
Intuition
To list all cities in each state as a single comma-separated string, we need to group the cities by state and concatenate the city names in sorted order.
Approach
- For MySQL:
- Use
GROUP_CONCAT
to aggregate city names for each state. - Use
ORDER BY
insideGROUP_CONCAT
to sort city names. - Group by
state
and order the result bystate
.
- Use
- For PostgreSQL:
- Use
STRING_AGG
to concatenate city names for each state. - Use
ORDER BY
withinSTRING_AGG
for city sorting. - Group by
state
and order the result bystate
.
- Use
- For Python (Pandas):
- Group the DataFrame by
state
. - Sort city names within each group and join them with commas.
- Sort the final DataFrame by
state
.
- Group the DataFrame by
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n log n)
, due to sorting cities within each state. - 🧺 Space complexity:
O(n)
, for storing the grouped and concatenated results.