#1724HardPremium on LC~58 min

Checking Existence of Edge Length Limited Paths II

Time ctor: O(nlogn + mlogm) query: O(logn) · Space O(nlogn + m) · Official statement on LeetCode

cpppython

Solutions

// Time:  ctor:  O(mlogm + m * α(n) + nlogn) ~= O(mlogm + nlogn)
//        query: O(α(n) + logn) ~= O(logn)
// Space: O(nlogn + m)

class DistanceLimitedPathsExist {
public:
    DistanceLimitedPathsExist(int n, vector<vector<int>>& edgeList)
     : uf_(n), tree_infos_(n) {
        sort(begin(edgeList), end(edgeList),
             [](const auto& a, const auto& b) {
                 return a[2] < b[2];
             });
        unordered_map<int, vector<pair<int, int>>> adj;
        for (const auto& edge : edgeList) {
            if (!uf_.union_set(edge[0], edge[1])) {
                continue;
            }
            adj[edge[0]].emplace_back(edge[1], edge[2]);
            adj[edge[1]].emplace_back(edge[0], edge[2]);
        }
        tree_infos_.init(adj);
    }
    
    bool query(int p, int q, int limit) {
        if (uf_.find_set(p) != uf_.find_set(q)) {
            return false;
        }
        return tree_infos_.max_weight(p, q) < limit;
    }

private:
    class TreeInfos {
    public:
        TreeInfos(int n)
         : L_(n)
         , R_(n)
         , P_(n)
         , W_(n)
         , C_(-1) {
            
        }
        
        void init(const unordered_map<int, vector<pair<int, int>>>& adj) {
            for (int i = 0; i < size(L_); ++i) {
                if (L_[i]) {
                    continue;
                }
                flood_fill(adj, i, -1, 0);
            }
        }
        
        bool is_ancestor(int a, int b) {
            return L_[a] <= L_[b] && R_[b] <= R_[a];
        }

        int max_weight(int a, int b) {
            int w = 0;
            if (!is_ancestor(a, b)) {
                w = max(w, binary_lift(a, b));
            }
            if (!is_ancestor(b, a)) {
                w = max(w, binary_lift(b, a));
            }
            return w;
        }

    private:
        int binary_lift(int a, int b) {
            int w = 0;
            for (int i = size(P_[a]) - 1; i >= 0; --i) {  // O(logN)
                if (i < size(P_[a]) && !is_ancestor(P_[a][i], b)) {
                    w = max(w, W_[a][i]);
                    a = P_[a][i];
                }
            }
            return max(w, W_[a][0]);
        }

        void flood_fill(const unordered_map<int, vector<pair<int, int>>>& children,
                        int curr, int parent, int weight) {
            if (parent != -1) {
                W_[curr].emplace_back(weight);
                P_[curr].emplace_back(parent);  // ancestors of the node i
            }
            for (int i = 0; i < size(P_[curr]); ++i) {
                if (i >= size(P_[P_[curr][i]])) {
                    break;
                }
                W_[curr].emplace_back(max(W_[curr][i], W_[P_[curr][i]][i]));
                P_[curr].emplace_back(P_[P_[curr][i]][i]);
            }
            L_[curr] = ++C_; 
            if (children.count(curr)) {
                for (const auto& [child, w] : children.at(curr)) {
                    if (child == parent) {
                        continue;
                    }
                    flood_fill(children, child, curr, w);
                }
            }
            R_[curr] = C_;
        }

        vector<int> L_;
        vector<int> R_;
        vector<vector<int>> P_;
        vector<vector<int>> W_;
        int C_;
    };

    class UnionFind {
    public:
        UnionFind(const int n)
         : set_(n)
         , rank_(n)
         , count_(n) {
            iota(set_.begin(), set_.end(), 0);
        }

        int find_set(const int x) {
           if (set_[x] != x) {
               set_[x] = find_set(set_[x]);  // Path compression.
           }
           return set_[x];
        }

        bool union_set(const int x, const int y) {
            int x_root = find_set(x), y_root = find_set(y);
            if (x_root == y_root) {
                return false;
            }
            if (rank_[x_root] < rank_[y_root]) {  // Union by rank.
                set_[x_root] = y_root;
            } else if (rank_[x_root] > rank_[y_root]) {
                set_[y_root] = x_root;
            } else {
                set_[y_root] = x_root;
                ++rank_[x_root];
            }
            --count_;
            return true;
        }

        int size() const {
            return count_;
        }

    private:
        vector<int> set_;
        vector<int> rank_;
        int count_;
    };

    UnionFind uf_;
    TreeInfos tree_infos_;
};

// Time:  ctor:  O(mlogm + m * α(n) * logm) ~= O(mlogm)
//        query: O(logm + α(n) * logm) ~= O(logm)
// Space: O(n + m * α(n) + m) ~= O(n + m)
class DistanceLimitedPathsExist2 {
public:
    DistanceLimitedPathsExist2(int n, vector<vector<int>>& edgeList)
     : uf_(n) {
        sort(begin(edgeList), end(edgeList),
             [](const auto& a, const auto& b) {
                 return a[2] < b[2];
             });
        for (const auto& edge : edgeList) {
            if (!uf_.union_set(edge[0], edge[1])) {
                continue;
            }
            uf_.snap();
            weights_.emplace_back(edge[2]);
        }
    }
    
    bool query(int p, int q, int limit) {
        int snap_id = distance(cbegin(weights_), lower_bound(cbegin(weights_), cend(weights_), limit)) - 1;
        if (snap_id == -1) {
            return false;
        }
        return uf_.find_set(p, snap_id) == uf_.find_set(q, snap_id);
        
    }

private:
    class VersionedUnionFind {
    public:
        VersionedUnionFind(const int n)
         : set_(n)
         , rank_(n)
         , snap_id_(0) {
             for (int i = 0; i < n; ++i) {
                 set_.set(i, i, snap_id_);
             }
        }

        int find_set(int x, int snap_id) {
            if (set_.get(x, snap_id) != x) {  // Path compression
                set_.set(x, find_set(set_.get(x, snap_id), snap_id), snap_id);
            }
            return set_.get(x, snap_id);
        }

        bool union_set(const int x, const int y) {
            int x_root = find_set(x, snap_id_), y_root = find_set(y, snap_id_);
            if (x_root == y_root) {
                return false;
            }
            if (rank_.get(x_root, snap_id_) < rank_.get(y_root, snap_id_)) {  // Union by rank.
                set_.set(x_root, y_root, snap_id_);
            } else if (rank_.get(x_root, snap_id_) > rank_.get(y_root, snap_id_)) {
                set_.set(y_root, x_root, snap_id_);
            } else {
                set_.set(y_root, x_root, snap_id_);
                rank_.set(x_root, rank_.get(x_root, snap_id_) + 1, snap_id_);
            }
            return true;
        }

        void snap() {
            ++snap_id_;
        }

    private:
        class SnapshotArray {
        public:
            SnapshotArray(int length) {
            }

            void set(int index, int val, int snap_id) {
                if (!snaps_.count(index)) {
                    snaps_[index][0] = 0;
                }
                snaps_[index][snap_id] = val;
            }

            int get(int index, int snap_id) {
                if (!snaps_.count(index)) {
                    snaps_[index][0] = 0;
                }
                const auto& it = prev(snaps_[index].upper_bound(snap_id));
                return it->second;
            }

        private:
            unordered_map<int, map<int, int>> snaps_;
        };

        SnapshotArray set_;
        SnapshotArray rank_;
        int snap_id_;
    };

    vector<int> weights_;
    VersionedUnionFind uf_;
};

Beginner Explanation

What is Checking Existence of Edge Length Limited Paths II?

Checking Existence of Edge Length Limited Paths II (LeetCode #1724) is a Hard problem that primarily trains graph.

How to think about it

  1. Restate the goal in your own words before coding.
  2. Work a tiny example by hand so the invariant becomes obvious.
  3. Identify the pattern — this problem aligns with graph algorithms.
  4. Only then translate the idea into code.

Why this problem matters

Hard problems force you to combine patterns and prove complexity carefully — interview gold. Official solution notes mention: Versioned Union Find, Binary Lifting.

AlgoForge explanations are original teaching notes. Always open the official problem statement on LeetCode for constraints and examples.

Interview Walkthrough

Interview approach for Checking Existence of Edge Length Limited Paths II

Opening (30–60 seconds)

  • Clarify inputs/outputs and edge cases (empty input, single element, duplicates, overflow).
  • State a brute force so the interviewer knows you can solve it naively.
  • Propose the optimal direction tied to graph algorithms.

Core solution narrative

  1. Define the state you track (pointers, DP cell, set membership, stack top, etc.).
  2. Explain the transition when you process the next element.
  3. Call out time (ctor: O(nlogn + mlogm) query: O(logn)) and space (O(nlogn + m)) before coding.
  4. Code cleanly; narrate variable names.

What interviewers listen for

  • Correctness on edge cases
  • Complexity honesty
  • Ability to discuss trade-offs (e.g., hash map space vs. sort + two pointers)

Follow-up questions they may ask

  • Can you solve it with less memory?
  • What if the input stream is infinite / doesn't fit in RAM?
  • How would tests look for adversarial inputs?

Optimized Approach

Optimized solution notes

The reference solutions on AlgoForge target ctor: O(nlogn + mlogm) query: O(logn) time and O(nlogn + m) space.

Pattern focus: graph algorithms

Use the pattern as a checklist:

  • graph algorithms — confirm the invariant holds after each step

Multiple methods appear in the source solutions — compare them and explain when each is preferable.

Implementation tips

  • Prefer readable names over micro-optimizations in interviews.
  • Extract helpers only when they clarify (e.g., expand-around-center, DFS visit).
  • After AC-level logic, re-scan for off-by-one and null checks.

Complexity Analysis

Complexity

Measure Bound
Time ctor: O(nlogn + mlogm) query: O(logn)
Space O(nlogn + m)

How to justify this in an interview

  • Time: count loops, map/set operations, and recursive branching; state average vs worst case if relevant.
  • Space: include hash maps, recursion stack, and output allocation when the problem asks for it.

If your implementation differs from the reference, re-derive big-O from your code — never memorize a complexity you cannot defend.

Common Mistakes

Common mistakes on Checking Existence of Edge Length Limited Paths II

  1. Skipping edge cases — empty collections, single-element inputs, max constraints.
  2. Wrong invariant for graph algorithms — updating state too early or too late.
  3. Mutating input unexpectedly when the problem forbids it.
  4. Off-by-one in windows, ranges, or binary search bounds.
  5. Ignoring overflow / precision for integer arithmetic problems.
  6. Overengineering — jumping to an advanced structure when a simpler approach works.

Alternative Approaches

Alternatives

The source file includes more than one method. Compare:

  1. Primary optimized path — best complexity for typical interviews.
  2. Secondary approach — often brute force, sorting-based, or space-optimized variant.

Practice articulating when you would pick each (constraints, readability, follow-ups).

Edge Cases

Edge cases checklist

  • Minimum input size
  • Maximum input size / time limits
  • Duplicates and already-sorted input
  • Negative numbers / zeros (if applicable)
  • Disconnected structures (graphs/trees)
  • Single path vs branching recursion depth

Pattern Recognition

Spotting this pattern

Signal phrases that point to graph algorithms:

  • Sorted input or ability to sort without changing the answer class
  • Need for contiguous subarray / substring → consider sliding window
  • Need for O(1) membership → hash set/map
  • Optimal substructure + overlapping subproblems → DP
  • Connectivity / components → graph DFS/BFS or Union-Find

Primary topics: graph.

Follow-up Interview Questions

Follow-ups

  1. How does the solution change if the input is a stream?
  2. Can you solve it in-place?
  3. What if duplicates must be handled differently?
  4. How would you parallelize the approach?
  5. Design tests that would break a buggy implementation.

Practice Recommendations

What to practice next

  1. Re-solve Checking Existence of Edge Length Limited Paths II in a second language (cpp, python).
  2. Drill 3–5 more problems tagged graph.
  3. Teach the solution out loud in under 5 minutes.
  4. Add this problem to your revision calendar in 3 days and 14 days.

Visualization

Conceptual diagram for Checking Existence of Edge Length Limited Paths II: show input structure (graph), highlight the moving parts of the graph algorithms approach, and annotate each step with the maintained invariant and complexity.

Study checklist

  • Read the official problem statement on LeetCode
  • Solve on paper / whiteboard first
  • Implement the graph algorithms approach
  • Verify edge cases from the checklist
  • State time and space complexity aloud
  • Compare with the AlgoForge reference solution
  • Schedule a revision session

Revision notes

Checking Existence of Edge Length Limited Paths II (#1724) — Hard. Pattern: graph algorithms. Complexity: ctor: O(nlogn + mlogm) query: O(logn) time / O(nlogn + m) space. Re-derive the invariant before coding.

FAQs

What is the time complexity of Checking Existence of Edge Length Limited Paths II?+

The reference solutions aim for ctor: O(nlogn + mlogm) query: O(logn) time and O(nlogn + m) space. Always re-derive complexity from the code you write in the interview.

What pattern does Checking Existence of Edge Length Limited Paths II use?+

It primarily maps to graph algorithms, within the broader topic of graph.

Is Checking Existence of Edge Length Limited Paths II good for interviews?+

Yes — as a Hard problem it is a solid practice target. Pair it with related problems in the same pattern family for spaced repetition.

Where can I read the official statement?+

Open the official LeetCode page for constraints and examples: https://leetcode.com/problems/checking-existence-of-edge-length-limited-paths-ii/