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.
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 <= 105
2 <= edges.length <= 105
edges[i].length == 2
1 <= ai, bi <= n
ai != bi
There are no repeated edges.
Solutions
Solution 1: Case Analysis
We first build the graph \(g\) using edges, and then find all nodes with odd degrees, denoted as \(vs\).
If the length of \(vs\) is \(0\), it means all nodes in the graph \(g\) have even degrees, so we return true.
If the length of \(vs\) is \(2\), it means there are two nodes with odd degrees in the graph \(g\). If we can directly connect these two nodes with an edge, making all nodes in the graph \(g\) have even degrees, we return true. Otherwise, if we can find a third node \(c\) such that we can connect \(a\) and \(c\), and \(b\) and \(c\), making all nodes in the graph \(g\) have even degrees, we return true. Otherwise, we return false.
If the length of \(vs\) is \(4\), we enumerate all possible pairs and check if any combination meets the conditions. If so, we return true; otherwise, we return false.
In other cases, we return false.
The time complexity is \(O(n + m)\), and the space complexity is \(O(n + m)\). Where \(n\) and \(m\) are the number of nodes and edges, respectively.