Add Edges to Make Degrees of All Nodes Even - Problem
Graph Degree Balancing Challenge
You're given an undirected graph with
Your mission is to determine if you can make every node have an even degree by adding at most 2 additional edges. The degree of a node is simply the number of edges connected to it.
Rules:
• You can add 0, 1, or 2 edges maximum
• No duplicate edges allowed
• No self-loops (a node cannot connect to itself)
Goal: Return
This problem tests your understanding of graph theory and the fundamental properties of graph connectivity.
You're given an undirected graph with
n nodes numbered from 1 to n, and a set of edges connecting some of these nodes. The graph might be disconnected, meaning some nodes might not be reachable from others.Your mission is to determine if you can make every node have an even degree by adding at most 2 additional edges. The degree of a node is simply the number of edges connected to it.
Rules:
• You can add 0, 1, or 2 edges maximum
• No duplicate edges allowed
• No self-loops (a node cannot connect to itself)
Goal: Return
true if it's possible to make all node degrees even, false otherwise.This problem tests your understanding of graph theory and the fundamental properties of graph connectivity.
Input & Output
example_1.py — Basic Case
$
Input:
n = 5, edges = [[1,2],[2,3],[3,2],[3,4],[4,2]]
›
Output:
true
💡 Note:
Node degrees: [2,4,3,1]. Nodes 3 and 4 have odd degrees. We can add edge (3,4) to make all degrees even: [2,4,4,2].
example_2.py — Impossible Case
$
Input:
n = 4, edges = [[1,2],[3,4]]
›
Output:
false
💡 Note:
All 4 nodes have degree 1 (odd). We'd need to add edges to pair them up, but we can only add 2 edges maximum. No way to make all 4 degrees even with just 2 additional edges.
example_3.py — Already Balanced
$
Input:
n = 4, edges = [[1,2],[2,3],[3,4],[4,1]]
›
Output:
true
💡 Note:
All nodes already have degree 2 (even). No additional edges needed.
Visualization
Tap to expand
Understanding the Visualization
1
Count Handshakes
Each person counts how many hands they've shaken (degree calculation)
2
Find Odd Counts
Identify people with odd handshake counts (odd-degree vertices)
3
Strategic Pairing
Plan additional handshakes to make everyone's count even
Key Takeaway
🎯 Key Insight: In any graph, the number of odd-degree vertices is always even due to the handshaking lemma. We just need to pair them up efficiently using at most 2 edges!
Time & Space Complexity
Time Complexity
O(n + m)
Single pass through edges O(m) plus checking nodes O(n), where m is number of edges
✓ Linear Growth
Space Complexity
O(n + m)
Store degree array O(n) and edge set O(m) for duplicate checking
⚡ Linearithmic Space
Constraints
- 1 ≤ n ≤ 105
- 0 ≤ edges.length ≤ min(2 * 105, n * (n-1) / 2)
- edges[i].length == 2
- 1 ≤ ai, bi ≤ n
- ai != bi
- There are no repeated edges
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code