KatInterview

Collapse Round-Trip Routes into Distinct City Pairs

Arrays & HashingAuto-graded · 13 test cases
EasyAuto-gradedArrays & Hashinghashingsortingdeduplication

Last 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:

  1. Two legs represent the same route if they involve the same two cities, in either order.
  2. Inside each returned pair, the two cities must be in ascending string order (the smaller string first, using standard Python string comparison).
  3. The returned list of pairs must be sorted in ascending order, comparing first by the first city and then by the second city.
  4. 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.
  5. Repeated legs on the same route appear only once in the output.
  6. 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.