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 trueif it is possible to make the degree of each node in the graph even, otherwise returnfalse.
The degree of a node is the number of edges connected to it.
graph LR
subgraph Original[" "]
A1(1) --- B1(2) & D1(4)
B1 --- D1 & C1(3) & E1(5)
C1 --- D1
end
subgraph After[" "]
A2(1) --- B2(2) & D2(4)
B2 --- D2 & C2(3) & E2(5)
C2 --- D2
D2 --- E2
end
Original --> After
linkStyle 12 stroke:red,stroke-width:2px
1
2
3
Input: n =5, edges =[[1,2],[2,3],[3,4],[4,2],[1,4],[2,5]]Output: trueExplanation: 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:
graph LR
subgraph Original[" "]
A1(1) --- B1(2)
C1(3) --- D1(4)
end
subgraph After[" "]
A2(1) --- B2(2) & C2(3)
C2 --- D2(4)
B2 --- D2
end
Original --> After
linkStyle 3 stroke:red,stroke-width:2px
linkStyle 5 stroke:red,stroke-width:2px
1
2
3
Input: n =4, edges =[[1,2],[3,4]]Output: trueExplanation: The above diagram shows a valid way of adding two edges.
Example 3:
graph TD;
A(1) --- B(2) & C(3) & D(4)
1
2
3
Input: n =4, edges =[[1,2],[1,3],[1,4]]Output: falseExplanation: It is not possible to obtain a valid graph with adding at most 2 edges.
The key insight is that a graph can have all nodes with even degrees if and only if the number of nodes with odd degrees is even (by the Handshaking Lemma). Since we can add at most two edges, we can only fix up to four odd-degree nodes. We check all possible ways to connect these odd-degree nodes with at most two new edges, ensuring no self-loops or duplicate edges.
classSolution:
defisPossible(self, n: int, edges: list[list[int]]) -> bool:
deg = [0] * (n +1)
st = set()
for a, b in edges:
deg[a] +=1 deg[b] +=1 st.add((min(a, b), max(a, b)))
odd = [i for i in range(1, n +1) if deg[i] %2]
if len(odd) ==0:
returnTrueif len(odd) ==2:
a, b = odd
if (min(a, b), max(a, b)) notin st:
returnTruefor i in range(1, n +1):
if i == a or i == b:
continueif (min(a, i), max(a, i)) notin st and (min(b, i), max(b, i)) notin st:
returnTruereturnFalseif len(odd) ==4:
o = odd
from itertools import combinations
for x, y in combinations(range(4), 2):
rem = [i for i in range(4) if i != x and i != y]
a1, b1 = o[x], o[y]
a2, b2 = o[rem[0]], o[rem[1]]
if (min(a1, b1), max(a1, b1)) notin st and (min(a2, b2), max(a2, b2)) notin st:
returnTruereturnFalsereturnFalse