Longest Eastward Chain of Cities from Raw CSV Text
Dynamic ProgrammingAuto-graded · 22 test casesLast updated
Parse CSV text with quoted fields, then find the longest chain of cities with increasing longitude and non-decreasing latitude, breaking ties by the smallest list of names.
Longest Eastward Chain of Cities
A travel app exports its stop list as one CSV string, csv_text. Parse it, then find the longest chain of cities that only moves east and never moves south.
Input
csv_text consists of lines separated by \n. The first line is always the header city_name,latitude,longitude. Every other line is one city record with exactly three fields: the name, the latitude, and the longitude. The latitude and longitude are decimal numbers.
Fields follow standard CSV quoting rules:
- A field may be wrapped in double quotes.
- Inside a quoted field, a comma is part of the text, not a separator.
- Inside a quoted field, two consecutive double quotes (
"") stand for one literal"character. - An unquoted field never contains a comma or a double quote.
The surrounding quotes are not part of the city name. For example, the field "City ""A""" is the name City "A".
Empty lines carry no record and must be ignored. If there are no records after the header, the answer is an empty list.
Chain rules
A chain is an ordered list of cities c_1, c_2, ..., c_k. It may use the records in any order, not only the order in which they appear in the input. Each step from c_i to c_{i+1} must satisfy both of these:
- The longitude of
c_{i+1}is strictly greater than the longitude ofc_i. - The latitude of
c_{i+1}is greater than or equal to the latitude ofc_i.
A single city is a valid chain of length 1.
Goal
Return the names of a chain with the maximum possible number of cities. If several chains have that maximum length, return the one whose list of names is lexicographically smallest. Compare the lists element by element, and compare individual names by ordinary string order (by character code). For example, ["A", "C"] is smaller than ["B", "A"].
Return the chosen chain as a list of city names, in travel order.
Constraints
- 0 <= number of city records N <= 1,000 (N is 0 only when just the header is present)
- -90.0 <= latitude <= 90.0
- -180.0 <= longitude <= 180.0
- City names are printable ASCII and at most 100 characters long.
- Different cities may share the same name, latitude, or longitude.
- A solution running in O(N^2) time is expected.
Examples
Example 1
Input: longest_eastward_chain('city_name,latitude,longitude\n"Denver, CO",39.7392,-104.9903\n"Omaha, NE",41.2565,-95.9345\n"Chicago, IL",41.8781,-87.6298\n"St. Louis, MO",38.6270,-90.1994')
Output: ['Denver, CO', 'Omaha, NE', 'Chicago, IL']
Example 2
Input: longest_eastward_chain('city_name,latitude,longitude\n"City ""A""",10.0,20.0\nCity B,15.0,20.0')
Output: ['City "A"']
Hints
Hint 1
Treat each city as a node, with an edge from city a to city b when b is strictly east of a and not south of a. Because longitude strictly increases along every edge, there are no cycles, so this is a longest-path problem on a DAG.
Hint 2
For parsing, do not split on commas. Use a CSV reader, or a small two-state scanner (inside quotes / outside quotes) that turns a doubled quote into one literal quote.
Hint 3
Compute, for each city, the longest chain starting there, by processing cities from the largest longitude down. For tie-breaking, do not store whole paths. Within each chain-length group, give every city a rank based on the pair (its name, rank of its best next city), so that comparing two chains takes constant work.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task has two independent parts: reading the CSV correctly, and finding the best chain.
Parsing. Splitting on commas breaks on names like "Denver, CO". Python's csv.reader implements the required quoting rules, including doubled quotes, so we feed it the whole text and skip the header and any empty rows. Without a library, a two-state scanner does the same job. Outside quotes, a comma ends a field and a newline ends a record. Inside quotes, "" yields one literal quote, a single " leaves the quoted state, and all other characters are literal.
Longest chain. Draw an edge from city a to city b when b has strictly larger longitude and latitude at least that of a. Longitude strictly increases along every edge, so the graph has no cycles. Let best[i] be the number of cities in the longest chain starting at i:
best[i] = 1 + max(best[j] over valid successors j), or 1 if there are none
If we process cities by descending longitude, every successor of i is already final when we reach i. Cities with equal longitude never connect, so their order among themselves does not matter.
Lexicographic tie-break. Storing and comparing whole paths would cost O(N) per comparison and O(N^3) overall. Instead, we rank chains layer by layer, by length:
- A chain of length
Lstarting ati(wherebest[i] = L) must continue to a successorjwithbest[j] = L - 1exactly. A larger value would contradictbest[i] = L, and a smaller one would make the chain too short. - Two chains of the same length compare first by their first name, then by the rest of the chain. So the smallest chain from
iis identified by the pair(name_i, rank of the smallest tail). - For each length, collect these pairs for all cities in that layer, sort the distinct pairs, and assign dense ranks. Identical chains (possible with duplicate names) get equal ranks.
- To choose
i's tail, take the valid successorjin layerL - 1that minimizes(name_j, rank[j]), and record it asnxt[i].
Finally, among cities with the overall maximum best, pick the one with the smallest (name, rank), then follow the nxt pointers to build the answer.
Why it is correct
- The descending-longitude order is a topological order, so the
bestrecurrence is the standard longest-path DP on a DAG. - Ranks are correct by induction on the length. For length 1, a chain is just a name, so ranking by name is exact. If ranks in layer
L - 1order the smallest chains lexicographically, then for lengthLthe comparison(name, rank of tail)is exactly the lexicographic comparison of the chains, since all candidate tails have the same length. Choosing the minimal tail therefore yields the smallest chain fromi. - Python string comparison is by code point, matching the required name ordering.
Complexity
- Time: O(N^2). The
bestcomputation checks all pairs, and the ranking step checks, for each city, all candidates once, since each city belongs to exactly one layer. Sorting adds O(N log N) comparisons of names up to 100 characters. - Space: O(N) for
best,rank,nxtand the parsed records.
Reference solution
import csv
import io
from typing import List
def longest_eastward_chain(csv_text: str) -> List[str]:
records = list(csv.reader(io.StringIO(csv_text)))
cities = []
for row in records[1:]:
if row:
name, lat, lon = row
cities.append((name, float(lat), float(lon)))
n = len(cities)
if n == 0:
return []
# best[i] = number of cities in the longest chain that starts at city i.
# Successors have strictly larger longitude, so handle cities in
# descending longitude order: all successors are finished by then.
order = sorted(range(n), key=lambda i: cities[i][2], reverse=True)
best = [1] * n
for i in order:
_, lat_i, lon_i = cities[i]
for j in range(n):
_, lat_j, lon_j = cities[j]
if lon_j > lon_i and lat_j >= lat_i:
if best[j] + 1 > best[i]:
best[i] = best[j] + 1
# rank[i] orders the canonical (smallest) optimal chain from city i among
# all cities with the same best[] value. Two chains of equal length compare
# by first name, then by the remaining tail, i.e. by (name, rank of tail).
rank = [0] * n
nxt = [-1] * n
top = max(best)
for size in range(1, top + 1):
group = [i for i in range(n) if best[i] == size]
keyed = []
for i in group:
name_i, lat_i, lon_i = cities[i]
if size == 1:
key = (name_i, -1)
else:
pick = None
pick_j = -1
for j in range(n):
_, lat_j, lon_j = cities[j]
if (lon_j > lon_i and lat_j >= lat_i
and best[j] == size - 1):
cand = (cities[j][0], rank[j])
if pick is None or cand < pick:
pick = cand
pick_j = j
nxt[i] = pick_j
key = (name_i, rank[pick_j])
keyed.append((key, i))
dense = {k: r for r, k in enumerate(sorted({k for k, _ in keyed}))}
for key, i in keyed:
rank[i] = dense[key]
start = min(
(i for i in range(n) if best[i] == top),
key=lambda i: (cities[i][0], rank[i]),
)
chain = []
while start != -1:
chain.append(cities[start][0])
start = nxt[start]
return chain