Add Edges to Make Degrees of All Nodes Even — LeetCode 2508 Python Solution

HardGraphHash Table
Problem
#2508
Reading time
4 min

The problem

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.

Example

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.

Python solution

Python
class Solution:
    def isPossible(self, n: int, edges: List[List[int]]) -> bool:
        g = defaultdict(set)
        for a, b in edges:
            g[a].add(b)
            g[b].add(a)
        vs = [i for i, v in g.items() if len(v) & 1]
        if len(vs) == 0:
            return True
        if len(vs) == 2:
            a, b = vs
            if a not in g[b]:
                return True
            return any(a not in g[c] and c not in g[b] for c in range(1, n + 1))
        if len(vs) == 4:
            a, b, c, d = vs
            if a not in g[b] and c not in g[d]:
                return True
            if a not in g[c] and b not in g[d]:
                return True
            if a not in g[d] and b not in g[c]:
                return True
            return False
        return False

Complexity

MeasureComplexity
TimeO(n + m)
SpaceO(n + m) auxiliary

Pattern: Depth-First Search

Follow one path to its end before trying the next — the default way to explore a graph. LeetCode 2508. Add Edges to Make Degrees of All Nodes Even is filed here because LeetCode tags it Graph, which is the vocabulary this hub collects.

The depth-first search guide has the Python template for the pattern and the 366 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2508. Add Edges to Make Degrees of All Nodes Even?
LeetCode 2508. Add Edges to Make Degrees of All Nodes Even is rated Hard on LeetCode.
What is the time complexity of LeetCode 2508. Add Edges to Make Degrees of All Nodes Even?
The Python solution on this page runs in O(n + m).
What is the space complexity of LeetCode 2508. Add Edges to Make Degrees of All Nodes Even?
The Python solution on this page uses O(n + m) auxiliary space.
What topics does LeetCode 2508. Add Edges to Make Degrees of All Nodes Even cover?
LeetCode 2508. Add Edges to Make Degrees of All Nodes Even is tagged Graph and Hash Table on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview