NeetCode #72LC-1436EasyArrays & Hashing
← Back to All Problems#72 · #1436 · Destination City(旅行终点站)
📌 Problem Statement & Constraints
You are given an array
paths where paths[i] = [cityA, cityB] means there is a direct path from cityA to cityB. Return the destination city, the one with no outgoing path, guaranteed to exist. Constraints: 1 <= paths.length <= 100; all city names are distinct strings.💡 Core Algorithmic Approaches
- The destination is the city that appears only as a second element across all pairs.
- Collect all source cities into a set, then find a city that appears as a destination but not in that set.
- Because the destination is guaranteed to exist and the graph is a straight chain, exactly one such city exists.
- An alternative is to start from any source and follow the chain until no outgoing edge remains.
💻 Benchmark Python3 Implementation
class Solution:
def destCity(self, paths: List[List[str]]) -> str:
sources = {a for a, _ in paths}
for _, b in paths:
if b not in sources: # no outgoing path from b
return b
return ""⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): one pass to build the source set and one pass to search for the destination.
💾 Space Complexity
O(n) for the source set.
⚠️ Interview Pitfalls & Follow-ups
- Collecting destinations instead: a city with no incoming path is the origin, not the destination.
- Counting occurrences of each city: counting is not enough -- a city could appear twice as a source and once as a destination. The set-based check is precise.
- Assuming the first pair's second element is the destination: the paths are unordered, so the chain may not start at
paths[0].
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Arrays & Hashing Problems
中文速览与面试要点
旅行终点站
给你一份旅游线路图,该线路图中的旅行线路用数组 paths 表示,其中 paths[i] = [cityAi, cityBi] 表示该线路将会从 cityAi 直接前往 cityBi。请你找出这次旅行的终点站,即没有任何可以通往其他城市的线路的城市。题目数据保证线路图会形成一条不存在循环的线路,因此恰有一个旅行终点站。约束:1 ≤ paths.length ≤ 100;paths[i].length == 2;1 ≤ cityAi.length, cityBi.length ≤ 10;cityAi != cityBi。
核心要点
- 集合差集(标准解) :把所有 出发地 cityAi 放入集合,然后遍历所有目的地 cityBi,第一个不在该集合中的即为终点站。
- 为什么终点站一定唯一 :题目保证线路构成一条无环的链,因此恰好有一个城市没有出边,即终点站。
- 等价视角 :这是一张有向图的「汇点」查找问题——入度 > 0 且出度 = 0 的节点。
- 复杂度 :建集合 O(n),查找 O(n)。
常见陷阱
- 对目的地集合取「不在出发地集合中」时误用对称差 :正确做法是「目的地 − 出发地」,用集合差集即可,不要用对称差( ^ )。
- 误以为终点站是「出现次数最少」的城市 :判断依据是「没有出边」,与出现次数无关。
- 用列表做 in 查询 : b not in list 是 O(n),整体退化为 O(n²)。必须用集合。
参考实现
class Solution:
def destCity(self, paths: list[list[str]]) -> str:
origins = {a for a, _ in paths} # 所有出发地
for _, b in paths:
if b not in origins: # 目的地不在出发地集合中 -> 终点站
return b
return '' # 题目保证有解,此行仅为完整性