Collapse Round-Trip Routes into Distinct City Pairs
Arrays & HashingAuto-graded · 13 test casesLast updated
Normalize directed city pairs into unordered ones, remove duplicates, and return them in sorted order, testing canonicalization with hashing and sorting.
Collapse Round-Trip Routes into Distinct City Pairs
A travel app stores a log of flight legs. Each leg is a two-element list [origin, destination] holding two city codes. For a route summary, the direction of travel does not matter: a leg from NYC to LAX and a leg from LAX to NYC describe the same route.
Given the log, produce the list of distinct unordered city pairs.
Task
Implement a function that takes the flight log and returns every distinct route exactly once, using these rules:
- Two legs represent the same route if they involve the same two cities, in either order.
- Inside each returned pair, the two cities must be in ascending string order (the smaller string first, using standard Python string comparison).
- The returned list of pairs must be sorted in ascending order, comparing first by the first city and then by the second city.
- A leg whose origin and destination are the same city produces a pair with that city repeated, for example
["SFO", "SFO"]. It is kept as a normal route. - Repeated legs on the same route appear only once in the output.
- If the log is empty, return an empty list.
City codes are compared exactly as given (case-sensitive, no trimming).
Input
flights: a list of[origin, destination]pairs, where each element is a string.
Output
A list of [city_a, city_b] lists with city_a <= city_b, with no duplicates, sorted ascending.
Constraints
0 <= len(flights) <= 10^5- Each leg contains exactly two non-empty strings.
- Each city string has length at most 20.
- Cities are compared as exact strings, with no case folding or whitespace trimming.
Examples
Example 1
Input: distinct_route_pairs([['NYC', 'LAX'], ['LAX', 'NYC'], ['ORD', 'ATL']])
Output: [['ATL', 'ORD'], ['LAX', 'NYC']]
Hints
Hint 1
Each leg is a directed pair, but you want a form that is identical for both directions. What simple operation on the two cities achieves this?
Hint 2
Put the smaller city first in every pair, then store the pairs in a set (as tuples) so duplicates disappear automatically.
Hint 3
Do not filter with origin < destination, since that drops routes that only appear in the reverse alphabetical direction. Finish by sorting the unique pairs and converting them to lists.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Each leg is a directed pair, but we only care about the unordered pair of cities. The fix is to convert each leg to a canonical form: put the smaller city first. Then [NYC, LAX] and [LAX, NYC] both become (LAX, NYC), so they are equal.
Steps:
- For every leg, sort its two cities and turn the result into a tuple.
- Insert each tuple into a set, which removes duplicates.
- Sort the set's tuples (Python compares tuples element by element, which matches the required ordering) and convert each tuple to a list.
Why it is correct
The mapping (a, b) -> (min(a, b), max(a, b)) is symmetric, so both directions of a route map to the same value. It is also injective on unordered pairs, so two different routes never map to the same value. The set of canonical pairs is therefore exactly the set of distinct unordered routes. Self-loops map to (a, a) and are kept. An empty log gives an empty set and so an empty list. A filter like origin < destination would wrongly drop routes that appear only in the reverse alphabetical direction, which normalization avoids.
Complexity
- Time: O(n + k log k), where n is the number of legs and k is the number of distinct routes (string comparisons add a factor bounded by the maximum city length).
- Space: O(k) for the set and the output.
Reference solution
from typing import List
def distinct_route_pairs(flights: List[List[str]]) -> List[List[str]]:
pairs = {tuple(sorted((origin, destination))) for origin, destination in flights}
return [list(pair) for pair in sorted(pairs)]