Problem 1436

Abstract / Summary

Given a list of routes, find the city that is only a destination and not a starting point.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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]
9 lines | 246 bytes | submitted November 13, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 80% (400k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Hash Table
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 8.11 | σ = 0.79

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
33 links | 22 authors | 10 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

10 solutions   November 13, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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