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:
false
💡 Note:
Current degrees: node 1=1, node 2=2, node 3=2, node 4=1, node 5=0. Nodes 1, 4, and 5 have odd degrees (3 total). Since we can add at most 2 edges affecting 4 endpoints, we cannot make all 3 odd-degree nodes 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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code