Determine if a Simple Graph Exists Problem
Description
LeetCode Problem 3656.
You are given an integer array degrees, where degrees[i] represents the desired degree of the i^th vertex.
Your task is to determine if there exists an undirected simple graph with exactly these vertex degrees.
A simple graph has no self-loops or parallel edges between the same pair of vertices.
Return true if such a graph exists, otherwise return false.
Example 1:
Input: degrees = [3,1,2,2]
Output: true
Explanation:

One possible undirected simple graph is:
- Edges: (0, 1), (0, 2), (0, 3), (2, 3)
- Degrees: deg(0) = 3, deg(1) = 1, deg(2) = 2, deg(3) = 2.
Example 2:
Input: degrees = [1,3,3,1]
Output: false
Explanation:
- degrees[1] = 3 and degrees[2] = 3 means they must be connected to all other vertices.
- This requires degrees[0] and degrees[3] to be at least 2, but both are equal to 1, which contradicts the requirement.
- Thus, the answer is false.
Constraints:
1 <= n == degrees.length <= 10^50 <= degrees[i] <= n - 1
Solution
Approach: Erdos-Gallai Theorem
A degree sequence is the degree sequence of a simple graph if and only if its sum is even and, after sorting in non-increasing order, for every k from 1 to n:
d[1] + ... + d[k] <= k * (k - 1) + min(d[k+1], k) + ... + min(d[n], k)
The k largest vertices can be joined to each other with at most k * (k - 1) edge endpoints, and each of the remaining vertices can absorb at most min(d_i, k) edges from them.
To test this in linear time after sorting, build prefix sums of the sorted degrees. Let p be the number of degrees that are at least k; it only decreases as k grows, so a pointer keeps it up to date. Among the vertices after the first k, those with index below p contribute k each and the rest contribute their own degree, which is a suffix sum. Return false as soon as one inequality fails (or the total is odd).
Complexity: O(n log n) time for the sort and O(n) extra space.
class Solution:
def simpleGraphExists(self, degrees: List[int]) -> bool:
n = len(degrees)
d = sorted(degrees, reverse=True)
total = sum(d)
if total % 2:
return False
pre = [0] * (n + 1)
for i, x in enumerate(d):
pre[i + 1] = pre[i] + x
p = n # number of degrees >= k
for k in range(1, n + 1):
while p > 0 and d[p - 1] < k:
p -= 1
# Erdos-Gallai: the k largest degrees fit among themselves plus edges to the rest
rhs = k * (k - 1) + k * max(0, p - k) + total - pre[max(p, k)]
if pre[k] > rhs:
return False
return True