Problem Description
Given an undirected graph with n nodes (labeled from 1 to n) and a list of edges, determine if it is possible to add at most two new edges (without self-loops or duplicate edges) so that every node ends up with an even degree.
Key Insights
- Only nodes with odd degree need to be “corrected” by adding edges.
- With at most two extra edges, there can only be 0, 2, or 4 nodes with odd degree.
- For 0 odd nodes, the graph already satisfies the requirements.
- For 2 odd nodes, either a direct edge between them (if not already present) or a two-edge solution via an intermediate node is possible.
- For 4 odd nodes, test all three possible pairings; each added edge must not be an existing edge.
- If there are any other number of odd nodes you cannot fix the degrees with at most 2 extra edges.
Space and Time Complexity
Time Complexity: O(m + n) where m is the number of given edges and n is the number of nodes. In the worst-case (2 odd nodes) an extra O(n) loop is performed. Space Complexity: O(m + n) due to storage for the edge set and degree counter.
Solution
The solution first computes the degree of each node and records all edges in a set for constant time edge-existence checks. After identifying the nodes with odd degree, we branch into three cases:
- If there are no odd nodes, the answer is true.
- If there are exactly 2 odd nodes, try to add a direct edge between them if it doesn’t already exist. If it does exist, check if there is an intermediate node which can connect to both odd nodes with two new valid edges.
- If there are exactly 4 odd nodes, test all three possible pairings of these nodes. If any valid pairing exists (i.e. neither edge in the pair is already present), return true. If none of the above cases succeed, return false.
Data structures used include:
- A set/hash table for quickly checking if an edge already exists.
- A simple array or list for counting degrees. The algorithm leverages careful case analysis to decide the outcome with a constant number of trials when the odd nodes count is small.