Reconstruct route from unordered travel tickets
Company: Pinterest
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates understanding of directed graph concepts and sequence reconstruction, assessing the ability to reason about ordered relationships and one-to-one incoming/outgoing connections between nodes.
Constraints
- 1 <= tickets.length <= 2e5
- City names are non-empty strings.
- Every city has at most one outgoing and at most one incoming ticket.
- The input is guaranteed to form exactly one valid chain.
- The output list has length tickets.length + 1.
Examples
Input: ([["A","B"],["B","C"]],)
Expected Output: ["A", "B", "C"]
Explanation: Simple 3-city chain already in order: A->B->C.
Input: ([["B","C"],["A","B"]],)
Expected Output: ["A", "B", "C"]
Explanation: Tickets are shuffled; A is the start because it never appears as a destination.
Input: ([["JFK","LAX"]],)
Expected Output: ["JFK", "LAX"]
Explanation: Boundary case: a single ticket yields a 2-city route.
Input: ([["D","E"],["A","B"],["C","D"],["B","C"]],)
Expected Output: ["A", "B", "C", "D", "E"]
Explanation: Fully shuffled 5-city chain; reconstruct A->B->C->D->E by following the outgoing map from A.
Input: ([["NYC","BOS"],["BOS","SEA"],["SEA","SFO"]],)
Expected Output: ["NYC", "BOS", "SEA", "SFO"]
Explanation: Longer chain in order across four cities.
Hints
- The start city is the only one that never appears as a destination (`to`). Track all destinations in a set and find the `from` that is not in it.
- Build a `from -> to` hash map so you can jump directly to the next city in O(1).
- Walk from the start, following the map and appending each city, until the current city has no outgoing ticket. No sorting needed — the chain is unique.