Add Edges to Make Degrees of All Nodes Even Problem
Description
LeetCode Problem 2508.
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] = [a_i, b_i] indicates that there is an edge between nodes a_i and b_i. 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.
Example 1:

Input: n = 5, edges = [[1,2],[2,3],[3,4],[4,2],[1,4],[2,5]]
Output: true
Explanation: The above diagram shows a valid way of adding an edge.
Every node in the resulting graph is connected to an even number of edges.
Example 2:

Input: n = 4, edges = [[1,2],[3,4]]
Output: true
Explanation: The above diagram shows a valid way of adding two edges.
Example 3:

Input: n = 4, edges = [[1,2],[1,3],[1,4]]
Output: false
Explanation: It is not possible to obtain a valid graph with adding at most 2 edges.
Constraints:
3 <= n <= 10^52 <= edges.length <= 10^5edges[i].length == 21 <= a_i, b_i <= na_i != b_i- There are no repeated edges.
Solution
Approach: Case Analysis on Odd-Degree Nodes
Each added edge changes the degree of two nodes, so we only care about nodes with odd degree. Collect them in vs.
- 0 odd nodes: nothing to do.
- 2 odd nodes
a,b: if they are not already connected, add the edgea-b. Otherwise find a third nodecthat is adjacent to neither, and adda-candc-b. - 4 odd nodes: we need two new edges pairing them up, so check the three possible pairings and accept one whose two edges do not already exist.
- Any other count (an odd count is impossible, 6 or more needs more than two edges): answer
false.
Adjacency is kept in a set per node so edge lookups are O(1).
Complexity: O(n + m) time and O(m) space, where m is the number of edges.
from collections import defaultdict
class Solution:
def isPossible(self, n: int, edges: List[List[int]]) -> bool:
g = defaultdict(set)
for a, b in edges:
g[a].add(b)
g[b].add(a)
vs = [i for i, v in g.items() if len(v) & 1]
if len(vs) == 0:
return True
if len(vs) == 2:
a, b = vs
if a not in g[b]:
return True
return any(a not in g[c] and c not in g[b] for c in range(1, n + 1))
if len(vs) == 4:
a, b, c, d = vs
if a not in g[b] and c not in g[d]:
return True
if a not in g[c] and b not in g[d]:
return True
if a not in g[d] and b not in g[c]:
return True
return False
return False