Problem solution · C++

Determine If a Simple Graph Exists

Determine If a Simple Graph Exists: a C++ solution using sliding window or two pointers. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Sliding window or two pointers
Source
Kamyu LeetCode Solutions
Length
29 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Sliding window or two pointers

For Determine If a Simple Graph Exists, the implementation maintains a moving interval and updates only the information that enters or leaves the window.

  1. Choose the invariant that makes a window valid or useful.
  2. Advance the right boundary and add the new element.
  3. Move the left boundary only as needed while maintaining the invariant and updating the answer.

Code notes

  • 29 lines of C++ from the credited upstream file determine-if-a-simple-graph-exists.cpp.
  • The implementation visibly relies on sequence storage.
  • 2 loop blocks detected.

Complexity

Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codeDetermine If a Simple Graph Exists · C++C++
Use this to learn the idea, then write your own version.
// Time:  O(nlogn)// Space: O(1) // Erdős–Gallai theorem, sort, prefix sum, two pointersclass Solution {public:    bool simpleGraphExists(vector<int>& degrees) {        // reference: https://en.wikipedia.org/wiki/Erd%C5%91s%E2%80%93Gallai_theorem        const auto& total = accumulate(cbegin(degrees), cend(degrees), 0LL);        if (total % 2) {            return false;        }        sort(begin(degrees), end(degrees), greater<int>());        int64_t lhs = 0, suffix1 = total, suffix2 = 0;        for (int k = 1, i = size(degrees) - 1; k <= size(degrees); ++k) {            lhs += degrees[k - 1];            suffix1 -= degrees[k - 1];            for (; i >= 0 && degrees[i] < k; --i) {                suffix2 += degrees[i];            };            const auto& rhs = static_cast<int64_t>(k) * (k - 1) + ((i - k + 1 > 0) ? static_cast<int64_t>(i - k + 1) * k + suffix2: suffix1);            if (!(lhs <= rhs)) {                return false;            }        }        return true;    }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗