Find Cities in Each State - Problem

You're working on a geographic data processing system that needs to organize city information by state. Given a database table containing city and state information, your task is to group all cities within each state into a single, comma-separated string.

The cities table contains:

  • state: The name of the state (varchar)
  • city: The name of the city within that state (varchar)

Your goal is to:

  1. Group cities by state
  2. Combine city names into comma-separated strings
  3. Sort cities alphabetically within each state
  4. Sort states alphabetically in the result

This is a classic SQL aggregation problem that tests your understanding of GROUP BY, string aggregation functions, and ORDER BY clauses.

Input & Output

example_1.sql β€” Basic Grouping
$ Input: cities table: +-------------+---------------+ | state | city | +-------------+---------------+ | California | Los Angeles | | California | San Francisco | | California | San Diego | | Texas | Houston | | Texas | Austin | | New York | Buffalo | +-------------+---------------+
β€Ί Output: +-------------+--------------------------------+ | state | cities | +-------------+--------------------------------+ | California | Los Angeles, San Diego, San Francisco | | New York | Buffalo | | Texas | Austin, Houston | +-------------+--------------------------------+
πŸ’‘ Note: Cities are grouped by state and concatenated alphabetically. California has 3 cities, New York has 1, and Texas has 2. States are ordered alphabetically in the result.
example_2.sql β€” Single City States
$ Input: cities table: +----------+--------+ | state | city | +----------+--------+ | Alaska | Juneau | | Hawaii | Honolulu | | Delaware | Dover | +----------+--------+
β€Ί Output: +----------+---------+ | state | cities | +----------+---------+ | Alaska | Juneau | | Delaware | Dover | | Hawaii | Honolulu| +----------+---------+
πŸ’‘ Note: When a state has only one city, that city appears alone in the result. States are still ordered alphabetically.
example_3.sql β€” Large Dataset
$ Input: cities table: +----------+----------+ | state | city | +----------+----------+ | Florida | Miami | | Florida | Tampa | | Florida | Orlando | | Florida | Jacksonville | | Ohio | Columbus | | Ohio | Cleveland| | Ohio | Cincinnati| +----------+----------+
β€Ί Output: +----------+----------------------------------------+ | state | cities | +----------+----------------------------------------+ | Florida | Jacksonville, Miami, Orlando, Tampa | | Ohio | Cincinnati, Cleveland, Columbus | +----------+----------------------------------------+
πŸ’‘ Note: Demonstrates handling of states with many cities. Florida has 4 cities and Ohio has 3, all properly sorted alphabetically within each state.

Constraints

  • 1 ≀ number of rows ≀ 104
  • 1 ≀ state.length, city.length ≀ 50
  • state and city contain only English letters and spaces
  • No duplicate (state, city) pairs in the input
  • At least one row will be present in the table

Visualization

Tap to expand
Tourism Brochure Organization Process1. Scattered CardsCA-LATX-HOUNY-NYCCA-SF2. Group by StateCATXNY3. Sort Within GroupsCALASDSFTXAUSHOUNYBUFNYC4. Create BrochuresCA: LA, SD, SFNY: BUF, NYCTX: AUS, HOU5. Final SortCA: LA, SD, SFNY: BUF, NYCTX: AUS, HOUSQL Query ProcessGROUP BY stateGroups rows bystate valueO(n) groupingORDER BY citySorts cities withineach groupO(k log k) per groupSTRING_AGGConcatenates sortedcities with commasO(k) per groupORDER BY stateSorts final resultsby state nameO(s log s)Complexity AnalysisTime: O(n log n)β€’ O(n) for groupingβ€’ O(k log k) for sorting cities per groupβ€’ O(s log s) for sorting statesSpace: O(n)β€’ O(n) for storing grouped resultsβ€’ O(n) for concatenated stringsβ€’ Efficient single-pass algorithm
Understanding the Visualization
1
Scatter the Cards
Individual city cards are scattered - each has a state and city name
2
Group by State
GROUP BY creates separate piles for each state
3
Sort Within Groups
Cities within each state pile are sorted alphabetically
4
Create Brochures
String aggregation combines cities into comma-separated lists
5
Final Organization
State brochures are arranged alphabetically
Key Takeaway
🎯 Key Insight: SQL's GROUP BY with string aggregation functions (GROUP_CONCAT, STRING_AGG, LISTAGG) provides an optimal O(n log n) solution that groups, sorts, and concatenates data efficiently in a single query operation.
Asked in
Amazon 45 Google 38 Microsoft 32 Meta 28
26.4K Views
Medium Frequency
~12 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
πŸ’‘ Explanation
AI Ready
πŸ’‘ Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen