Skip to content

2508. Add Edges to Make Degrees of All Nodes Even

Description

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: Hash Table

  • Time complexity: O(n+edges.length)
  • Space complexity: O(n+edges.length)

 

JavaScript

js
/**
 * @param {number} n
 * @param {number[][]} edges
 * @return {boolean}
 */
const isPossible = function (n, edges) {
  const graph = Array.from({ length: n }, () => []);
  const oddNodes = [];

  for (const [u, v] of edges) {
    const a = u - 1;
    const b = v - 1;

    graph[a].push(b);
    graph[b].push(a);
  }

  for (let node = 0; node < n; node++) {
    if (graph[node].length % 2) {
      oddNodes.push(node);
    }
  }

  if (oddNodes.length === 0) return true;

  if (oddNodes.length === 2) {
    const [a, b] = oddNodes;

    if (!graph[a].includes(b)) return true;

    for (let node = 0; node < n; node++) {
      if (node === a || node === b) continue;

      if (!graph[node].includes(a) && !graph[node].includes(b)) {
        return true;
      }
    }
  }

  if (oddNodes.length === 4) {
    const [a, b, c, d] = oddNodes;

    if (!graph[a].includes(b) && !graph[c].includes(d)) return true;
    if (!graph[a].includes(c) && !graph[b].includes(d)) return true;
    if (!graph[a].includes(d) && !graph[b].includes(c)) return true;
  }

  return false;
};

Released under the MIT license