Add Edges to Make Degrees of All Nodes Even - Problem
There is an undirected graph consisting of n nodes numbered from 1 to n. You are given the integer n and a 2D array edges where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi. The graph can be disconnected.
You can add at most two additional edges (possibly none) to this graph so that there are no repeated edges and no self-loops.
Return true if it is possible to make the degree of each node in the graph even, otherwise return false.
The degree of a node is the number of edges connected to it.
Input & Output
Example 1 — Basic Case
$
Input:
n = 5, edges = [[1,2],[2,3],[3,4]]
›
Output:
true
💡 Note:
Current degrees: [1,1,2,1,0]. Nodes 1,2,4 have odd degrees. We can add edges (1,4) and (5,2) to make all degrees even.
Example 2 — Already Valid
$
Input:
n = 4, edges = [[1,2],[3,4]]
›
Output:
true
💡 Note:
All nodes have degree 1 (odd). We have 4 odd nodes, so we can add edges (1,3) and (2,4) to make all degrees even.
Example 3 — Impossible Case
$
Input:
n = 4, edges = [[1,2],[1,3],[1,4]]
›
Output:
false
💡 Note:
Node 1 has degree 3, nodes 2,3,4 have degree 1. That's 4 odd nodes, but all pairs involve node 1, making it impossible with only 2 edges.
Constraints
- 1 ≤ n ≤ 105
- 0 ≤ edges.length ≤ 105
- edges[i].length == 2
- 1 ≤ ai, bi ≤ n
- ai ≠ bi
- There are no repeated edges
Visualization
Tap to expand
Understanding the Visualization
1
Input Graph
Graph with some nodes having odd degrees
2
Count Analysis
Apply Handshaking Lemma to count odd nodes
3
Strategic Addition
Add at most 2 edges to make all degrees even
Key Takeaway
🎯 Key Insight: Use Handshaking Lemma - odd-degree node count is always even, enabling strategic pairing
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code