Problem 1466

Abstract / Summary

Find the minimum number of edge reversals needed so every city connects to city zero in a tree structure.

Note

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

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
30 lines | 813 bytes | submitted September 13, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 66% (500k+ submissions).

Typical patterns to solve this problem:
  • Breadth First Search
  • Depth First Search
  • Graph Theory
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 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 increments result because 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 6 | μ = 6.31 | σ = 1.41

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++ 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
27 links | 16 authors | 8 languages

Videos

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

Similar Problems

1 similar problem

Solved On The Same Day

7 easy 6 medium
14 solutions   September 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