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
Add Edges to Make All Degrees EvenInput Graph123Deg: 1Deg: 1Deg: 2AnalysisOdd degree nodes: 2Handshaking Lemma:Even count ✓Solution123Deg: 2Deg: 2Deg: 2Result: true (added 1 edge to connect odd-degree nodes)
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
Asked in
Google 25 Microsoft 18 Amazon 15
28.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen