#3607
Power Grid Maintenance
MediumArrayHash TableDepth-First SearchBreadth-First SearchUnion-FindGraph TheoryHeap (Priority Queue)Ordered SetGraph TraversalUnion-Find
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
Use graph traversal to group stations into components and maintain a sorted list of operational stations for efficient checks.
⚙️
Algorithm
3 steps- 1Step 1: Use DFS/BFS to identify connected components and store operational stations in sorted sets.
- 2Step 2: For query type [1, x], check if x is online; if not, find the smallest operational id in its component.
- 3Step 3: For query type [2, x], mark x as offline and update the sorted set.
solution.py31 lines
1def powerGridMaintenance(c, connections, queries):
2 from collections import defaultdict
3 online = [True] * (c + 1)
4 graph = defaultdict(list)
5 for u, v in connections:
6 graph[u].append(v)
7 graph[v].append(u)
8 components = {}
9 def dfs(node, comp_id):
10 stack = [node]
11 while stack:
12 n = stack.pop()
13 if n not in components:
14 components[n] = comp_id
15 for neighbor in graph[n]:
16 stack.append(neighbor)
17 for station in range(1, c + 1):
18 if station not in components:
19 dfs(station, station)
20 results = []
21 for query in queries:
22 if query[0] == 1:
23 x = query[1]
24 if online[x]:
25 results.append(x)
26 else:
27 # Find smallest operational in component
28 results.append(-1) # Placeholder
29 else:
30 online[query[1]] = False
31 return resultsℹ
Complexity note: Graph traversal takes O(n), and maintaining sorted sets incurs log n for updates.
- 1Understanding connected components is crucial.
- 2Efficient data structures like sorted sets help in quick lookups.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.