Skip to main content

Add Edges to Make Degrees of All Nodes Even - Solution & Explanation

HardHash TableGraph25 min readAsked at: Hrt
Practice this problem

Problem Statement

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.

Approach Overview

Problem Overview: You are given an undirected graph with n nodes and a list of edges. The task is to determine whether you can add at most two new edges so that every node ends up with an even degree. Multiple edges between the same pair and self-loops are not allowed.

The key observation from graph theory: a graph has all even degrees only when the number of odd-degree vertices is zero. Adding one edge flips the parity (odd/even) of exactly two vertices. This means only a few configurations of odd-degree nodes are fixable with at most two added edges.

Approach 1: Divide and Conquer Approach (O(n + m))

Start by building a graph representation using adjacency sets from the edge list. Track the degree of every node and collect all nodes with odd degree. Because each added edge changes the parity of two nodes, there are only three possible cases to check: 0 odd nodes, 2 odd nodes, or 4 odd nodes.

If there are zero odd nodes, the graph already satisfies the condition. If there are two odd nodes a and b, try directly connecting them. If an edge already exists, search for an intermediate node x such that neither (a,x) nor (b,x) exists. If four odd nodes exist, try pairing them in the three possible combinations and verify that the required edges do not already exist. Using adjacency sets allows constant-time edge existence checks. Building the graph takes O(n + m) time and the pairing checks are constant, so the overall complexity remains O(n + m) with O(n + m) space.

Approach 2: Iterative Approach Using Stack (O(n + m))

An iterative traversal can be used to compute node degrees and validate graph structure. Push nodes onto a stack and process their adjacency lists to count incident edges. This traversal ensures every vertex and edge is visited once, giving a complete degree map.

After computing degrees, push odd-degree nodes into a container and apply the same parity rules: only 0, 2, or 4 odd vertices can potentially be fixed. Use the adjacency HashSet to test candidate edges while iterating through possible pairings. The stack-based traversal avoids recursion and works well when the graph is large or when recursion limits are a concern. Time complexity is O(n + m) and space complexity is also O(n + m) due to adjacency storage and the stack.

Both approaches rely on efficient edge existence checks using a hash table structure and standard graph degree properties. Understanding the parity behavior of vertices drastically reduces the search space from exponential possibilities to a few constant checks.

Recommended for interviews: The divide-and-conquer style parity analysis is what interviewers typically expect. It shows you recognize the odd-degree constraint and can reduce the problem to checking a few valid pairings. A brute-force mindset (trying many edges) shows understanding, but recognizing the parity rule and validating with hash lookups demonstrates strong graph reasoning.

Approach 1: Divide and Conquer Approach

This approach breaks down a problem into smaller subproblems that are solved recursively. It works well when the problem can be divided into smaller, similar problems and can be combined to form the solution to the original problem.

This C solution implements the merge sort algorithm. The function mergeSort is a recursive function that divides the array into two halves and calls itself for the two halves, and then calls the merge function to merge the two halves. This approach sorts the array in-place.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n log n) because the array is recursively divided into two halves. Space Complexity: O(n) because of the temporary arrays L and R.

Try this approach in the editor →

Approach 2: Iterative Approach Using Stack

An iterative approach can be ideal for avoiding the memory overhead of recursion. By using a stack to simulate the call stack, we can perform merge sort iteratively. This trades additional stack space for a potentially more memory-efficient solution.

This C program performs iterative merge sort using a bottom-up approach, starting with subarrays of size 1 and doubling in size each iteration.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n log n). Space Complexity: O(n) due to the temporary storage for merging.

Try this approach in the editor →

Approach 3: 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.

Code

Python

Java

C++

Go

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Divide and Conquer Approach

Time Complexity: O(n log n) because the array is recursively divided into two halves. Space Complexity: O(n) because of the temporary arrays L and R.

Iterative Approach Using Stack

Time Complexity: O(n log n). Space Complexity: O(n) due to the temporary storage for merging.

Case Analysis—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Divide and Conquer Degree AnalysisO(n + m)O(n + m)Best general solution. Quickly checks odd-degree configurations using adjacency hash sets.
Iterative Approach Using StackO(n + m)O(n + m)Useful when performing explicit graph traversal or avoiding recursion while computing node degrees.

Video Solution

Weekly Contest 324 | Add Edges to Make Degrees of All Nodes Even • codingMohan • 919 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Add Edges to Make Degrees of All Nodes Even easy or hard?
The problem is classified as Hard because it requires recognizing graph parity constraints and reducing the search space to a few valid configurations. Once the odd-degree insight is understood, the implementation becomes straightforward with hash sets.
Add Edges to Make Degrees of All Nodes Even Python/Java solution
Implement the solution by building an adjacency set for each node, computing degrees, and storing odd-degree vertices. Then test valid pairings depending on whether there are two or four odd nodes. This logic works consistently across Python, Java, C++, and other languages.
How to solve Add Edges to Make Degrees of All Nodes Even in O(n)?
Build adjacency sets and compute degrees for all nodes while iterating through the edges. Collect nodes with odd degree and handle three cases: 0, 2, or 4 odd nodes. Validate whether the required edges can be added without duplicates using constant-time hash lookups.
What is the best approach for Add Edges to Make Degrees of All Nodes Even?
The optimal approach analyzes the parity of node degrees in the graph. Count nodes with odd degree and check whether they can be fixed by adding at most two edges. Using adjacency hash sets allows constant-time edge existence checks, resulting in an overall time complexity of O(n + m).
Is Add Edges to Make Degrees of All Nodes Even asked at Google/Amazon/Meta?
Graph parity and degree manipulation problems frequently appear in interviews at companies like Google, Amazon, and Meta. Variations often test understanding of Eulerian graph properties, adjacency sets, and efficient edge validation.
What data structure is used in Add Edges to Make Degrees of All Nodes Even?
The solution uses graph adjacency sets implemented with hash tables. These structures store neighbors of each node and allow O(1) average-time checks to determine whether an edge already exists between two vertices.
What is the time complexity of Add Edges to Make Degrees of All Nodes Even?
The optimal solution runs in O(n + m) time, where n is the number of nodes and m is the number of edges. Building adjacency sets and counting node degrees takes linear time, and the final parity checks involve only a few constant combinations.

Ready to solve this problem?

Practice Add Edges to Make Degrees of All Nodes Even with our built-in code editor and test cases.

Practice on FleetCode