Python 1436.py
class Solution:
def destCity(self, paths: List[List[str]]) -> str:
depart = set()
arrive = set()
for a, b in paths:
depart.add(a)
arrive.add(b)
return list(arrive - depart)[0]
Difficulty
and has an acceptance rate of about 80% (400k+ submissions).
Typical patterns to solve this problem:
- Array
- Hash Table
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the problem of finding the destination city in a list of directed paths. Each path is represented as a pair [origin, destination]. The algorithm builds two collections: one containing all origin cities and another containing all destination cities. The destination city is the one that never appears as an origin. By computing the set difference between destinations and origins, the code isolates the unique city that satisfies this condition and returns it.
Key Steps
The core logic is divided into three distinct phases: initialization, population of sets, and extraction of the result.
depart = set()
arrive = set()
In the first phase, two empty sets are created. The depart set will hold every city that appears as a starting point, while the arrive set will hold every city that appears as an endpoint.
for a, b in paths:
depart.add(a)
arrive.add(b)
During the second phase, the code iterates over each [origin, destination] pair in the input list. For each pair, the origin a is added to depart and the destination b is added to arrive. Because sets automatically discard duplicate entries, the collections contain each city only once regardless of how many times it appears in the input.
return list(arrive - depart)[0]
The final phase computes the set difference arrive - depart, which yields the set of cities that appear only as destinations. Converting this set to a list and selecting the first element returns the required destination city. The problem guarantees that exactly one such city exists, so indexing [0] is safe.
Edge Cases Handled
The algorithm gracefully handles inputs where multiple paths share the same origin or destination. Since both depart and arrive are sets, repeated occurrences of a city do not affect the final result. If the input contains a single path, the sets will each contain one element, and the difference operation will correctly identify the destination. The code also works when the list of paths is unsorted; the order of iteration does not influence the set contents, ensuring correctness regardless of input ordering.
Performance Optimizations
Using sets for depart and arrive provides constant-time insertion and membership checks, which keeps the overall processing time linear with respect to the number of paths. The set difference operation is also linear in the size of the sets, avoiding nested loops or repeated scans. By converting the difference to a list only once and accessing the first element, the implementation avoids unnecessary copying or iteration over the result. This combination of data structures and operations yields an efficient solution that scales well with larger inputs.
ELI5 - Simplified Explanation
Imagine you have a big stack of travel tickets, and each ticket shows a trip from one city to another. Some cities are where you start a journey, and some cities are where you finish.
To figure out the very final destination, you can put all the start cities into one bucket and all the end cities into another bucket. When you look at these two buckets, you keep the cities where you only ever landed but never left from. Since you started at one place and hopped around until you could not go any further, the city that is in the arrival bucket but never in the departure bucket is the end of the line.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||
| WalkCCC | Python | ||||||||||
| leetcode.ca | C++ | Python | JS | Java | Go | Rust | TS | ||||
| Progiez | C++ | Python | Java | ||||||||
| github | BigEggStudy | C# | |||||||||
| black-shadows | C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fsq | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| lzl124631x | C++ | ||||||||||
| muhammadfarhankt | Go | ||||||||||
| pruthvikp | Python | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | Python | ||||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, Rust, TypeScript | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fsq | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| lzl124631x | C++ | ||||||||||
| muhammadfarhankt | Go | ||||||||||
| pruthvikp | Python | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| YuriSpiridonov | Python |
Videos
Solved On The Same Day
- problem 1446: Consecutive Characters
- problem 1450: Number of Students Doing Homework at a Given Time
- problem 1423: Maximum Points You Can Obtain from Cards
- problem 1432: Max Difference You Can Get From Changing an Integer
- problem 1433: Check If a String Can Break Another String
- problem 1447: Simplified Fractions
- problem 1451: Rearrange Words in a Sentence
- problem 1452: People Whose List of Favorite Companies Is Not a Subset of Another List
- problem 1483: Kth Ancestor of a Tree Node
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality