#2508
Add Edges to Make Degrees of All Nodes Even
HardHash TableGraph TheoryGraph TheorySet Operations
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution leverages the fact that the number of nodes with odd degrees must be 0, 2, or 4 for it to be possible to make all degrees even. This allows us to directly check combinations without brute-forcing.
⚙️
Algorithm
5 steps- 1Step 1: Count the degree of each node from the given edges.
- 2Step 2: Identify nodes with odd degrees.
- 3Step 3: If there are 0 odd nodes, return true.
- 4Step 4: If there are 2 odd nodes, check if they can be connected without creating a duplicate edge.
- 5Step 5: If there are 4 odd nodes, check if any two can be connected without creating a duplicate edge.
solution.py22 lines
1# Full working Python code
2from collections import defaultdict
3
4def canMakeDegreesEven(n, edges):
5 degree = [0] * (n + 1)
6 edgeSet = set()
7 for a, b in edges:
8 degree[a] += 1
9 degree[b] += 1
10 edgeSet.add((a, b))
11 edgeSet.add((b, a))
12 odd_nodes = [i for i in range(1, n + 1) if degree[i] % 2 != 0]
13 if len(odd_nodes) == 0:
14 return True
15 if len(odd_nodes) == 2:
16 return (odd_nodes[0], odd_nodes[1]) not in edgeSet
17 if len(odd_nodes) == 4:
18 for i in range(4):
19 for j in range(i + 1, 4):
20 if (odd_nodes[i], odd_nodes[j]) not in edgeSet:
21 return True
22 return Falseℹ
Complexity note: This complexity is due to counting degrees and checking pairs of odd nodes, which is linear in relation to the number of edges.
- 1The degree of a node is even if it has an even number of edges connected to it.
- 2Adding an edge between two nodes affects the degree of both nodes.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.