Python 1466.py
class Solution:
def minReorder(self, n: int, connections: List[List[int]]) -> int:
okay = defaultdict(list)
bad = defaultdict(list)
for c in connections:
bad [c[0]].append(c[1])
okay[c[1]].append(c[0])
result = 0
done = set()
todo = [ 0 ]
while todo:
next = [ ]
for t in todo:
if t in done:
continue
done.add(t)
for o in okay[t]:
if o not in done:
next += [ o ]
for b in bad[t]:
if b not in done:
next += [ b ]
result += 1
todo = next
return result
Difficulty
and has an acceptance rate of about 66% (500k+ submissions).
Typical patterns to solve this problem:
- Breadth First Search
- Depth First Search
- Graph Theory
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 determining the minimum number of edges that must be reversed so that every city can reach city 0 in a directed tree. It builds two adjacency structures: one for correctly oriented edges (okay) and one for edges that point away from the destination (bad). A breadth-first traversal starting from city 0 visits all reachable nodes, counting each traversed “bad” edge as a required reversal.
Construction of adjacency maps
okay = defaultdict(list)
bad = defaultdict(list)
for c in connections:
bad [c[0]].append(c[1])
okay[c[1]].append(c[0])
Each connection [a, b] is interpreted as a directed road from a to b. The road is stored in bad under its source city because it would need to be reversed to allow travel toward city 0. Simultaneously, the reverse direction is stored in okay under the destination city, representing a path that already leads toward the root.
Traversal initialization
result = 0
done = set()
todo = [0]
result accumulates the number of reversals. done tracks cities that have already been processed, preventing repeated work. todo holds the frontier of the breadth-first search, seeded with the root city 0.
Breadth-first processing loop
while todo:
next = []
for t in todo:
if t in done:
continue
done.add(t)
for o in okay[t]:
if o not in done:
next += [o]
for b in bad[t]:
if b not in done:
next += [b]
result += 1
todo = next
The loop continues until no new cities are discovered. For each city t taken from the current frontier:
- The city is marked as visited.
- All neighbors reachable via already correctly oriented edges (
okay[t]) are added to the next frontier without affecting the reversal count. - All neighbors reachable only through incorrectly oriented edges (
bad[t]) are also added, but each such addition incrementsresultbecause that edge must be flipped to enable travel toward the root.
The use of a separate next list isolates the current level from the upcoming one, ensuring that each edge is examined exactly once.
Edge-case handling
The algorithm gracefully handles the situation where the input graph contains a single city (n == 1). In that case connections is empty, both adjacency maps remain empty, the initial todo list contains only city 0, and the while-loop terminates after the first iteration without modifying result. The returned value is correctly 0.
When multiple edges converge on the same city, the okay map may contain several entries for that city. The traversal checks the done set before enqueuing each neighbor, guaranteeing that duplicate entries do not cause redundant processing or double counting of reversals.
If the input includes isolated sub-trees that are already reachable from city 0 via correctly oriented edges, those sub-trees are explored through the okay adjacency without incrementing result. Conversely, any sub-tree that can only be reached through a mis-directed edge contributes exactly one to the reversal count, reflecting the necessity to flip that edge.
Performance-related choices
The separation of edges into okay and bad eliminates the need for conditional checks during traversal to determine the direction of each edge. By pre-classifying edges, the inner loops can directly iterate over the appropriate neighbor list, reducing per-iteration overhead.
Using a set for done provides constant-time membership tests, which is crucial when the number of cities grows large. The algorithm avoids recursion, thereby eliminating the risk of stack overflow and ensuring that memory usage remains bounded by the size of the frontier and the visited set.
The frontier is stored as a plain Python list, and new nodes are appended using list concatenation (next += [node]). Although this creates a temporary list for each addition, the overall number of concatenations equals the number of edges, keeping the total work linear in the size of the graph.
By processing each city exactly once and examining each edge exactly once-either as an okay neighbor or a bad neighbor-the implementation achieves an efficient traversal that scales directly with the input size.
ELI5 - Simplified Explanation
Imagine a big, messy map of cities connected by one-way roads. Some of these roads lead toward the center city where everything is, and some lead away from it. To make sure everyone can reach the center, some roads need to be turned around.
The code starts by sorting all the roads into two piles. One pile has roads that already point toward the center, and the other pile has the roads that are pointing in the wrong direction.
A list is created to keep track of the cities that have been checked, starting with the center city. The computer then looks at every road connected to those cities. When it finds a road that points the wrong way, it counts that as a road that needs to be flipped. It keeps moving outward from city to city, exploring all the paths until every single city has been visited. Every time it finds a road that was pointing away from the center, it adds one to the total count of roads that must be fixed. After checking every path, the final count shows exactly how many roads need to be turned around to keep the traffic flowing to the right place.
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++ | Java | Python | TS | ||||
| WalkCCC | C++ | Java | |||||||
| leetcode.ca | C++ | Java | Python | Go | Rust | TS | |||
| Progiez | C++ | Java | Python | ||||||
| github | BigEggStudy | C# | |||||||
| black-shadows | C++ | ||||||||
| charles-wangkai | Java | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| MacJim | C++ | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| vthwang | Java | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| BigEggStudy | C# | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| MacJim | C++ | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| vthwang | Java |
Videos
Similar Problems
- problem 2858: Minimum Edge Reversals So Every Node Is Reachable
Solved On The Same Day
- problem 521: Longest Uncommon Subsequence I
- problem 557: Reverse Words in a String III
- problem 697: Degree of an Array
- problem 771: Jewels and Stones
- problem 819: Most Common Word
- problem 1700: Number of Students Unable to Eat Lunch
- problem 2073: Time Needed to Buy Tickets
- problem 399: Evaluate Division
- problem 435: Non-overlapping Intervals
- problem 547: Number of Provinces
- problem 841: Keys and Rooms
- problem 2462: Total Cost to Hire K Workers
- problem 2542: Maximum Subsequence Score
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