#3812

Minimum Edge Toggles on a Tree

Hard
TreeDepth-First SearchGraph TheoryTopological SortSortingGraph TraversalBit Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Use DFS to traverse the tree and determine which edges need toggling based on the difference between start and target colors.

⚙️

Algorithm

3 steps
  1. 1Step 1: Perform DFS from any root node, tracking the current toggle state.
  2. 2Step 2: For each node, if its color differs from the target, toggle the edge to its parent.
  3. 3Step 3: Collect the indices of toggled edges and return them.
solution.py18 lines
1def minEdgeToggles(n, edges, start, target):
2    from collections import defaultdict
3    graph = defaultdict(list)
4    for i, (u, v) in enumerate(edges):
5        graph[u].append((v, i))
6        graph[v].append((u, i))
7    result = []
8    def dfs(node, parent, toggle):
9        current_color = start[node] ^ toggle
10        if current_color != target[node]:
11            toggle ^= 1
12            if parent != -1:
13                result.append(edges[parent][1])
14        for neighbor, edge_index in graph[node]:
15            if neighbor != parent:
16                dfs(neighbor, edge_index, toggle)
17    dfs(0, -1, 0)
18    return sorted(result) if len(result) % 2 == 0 else [-1]

Complexity note: DFS visits each node once, making it linear in terms of the number of nodes.

  • 1DFS is efficient for tree traversal.
  • 2Toggling affects both connected nodes, so track the toggle state.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.