Problem solution · C++

Kth Smallest Path Xor Sum

Kth Smallest Path Xor Sum: a C++ solution using depth-first search. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Depth-first search
Source
Kamyu LeetCode Solutions
Length
117 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

Depth-first search

For Kth Smallest Path Xor Sum, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.

  1. Define the state carried into one recursive or stack frame.
  2. Mark or choose the current state before exploring children.
  3. Combine child results or undo the choice when the branch finishes.

Code notes

  • 117 lines of C++ from the credited upstream file kth-smallest-path-xor-sum.cpp.
  • The implementation visibly relies on sequence storage.
  • 12 loop blocks detected, together with recursive traversal.

Complexity

Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.

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 codeKth Smallest Path Xor Sum · C++C++
Use this to learn the idea, then write your own version.
// Time:  O(n * (logn)^2 + qlogn)// Space: O(n + q) #include <ext/pb_ds/assoc_container.hpp>#include <ext/pb_ds/tree_policy.hpp>using namespace __gnu_pbds; // iterative dfs, small-to-large merging, ordered setclass Solution {public:    vector<int> kthSmallest(vector<int>& par, vector<int>& vals, vector<vector<int>>& queries) {        vector<vector<int>> adj(size(par));        for (int u = 0; u < size(par); ++u) {            const auto& p = par[u];            if (p != -1) {                adj[p].emplace_back(u);            }        }        vector<vector<int>> lookup(size(adj));        for (int i = 0; i < size(queries); ++i) {            lookup[queries[i][0]].emplace_back(i);        }        const auto& iter_dfs = [&]() {            using ordered_set = tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update>;            vector<ordered_set> os(size(adj));            vector<int> idxs(size(adj));            iota(begin(idxs), end(idxs), 0);            const auto& small_to_large_merge = [&](auto& i, auto& j) {  // Total Time: O(n * (logn)^2)                if (size(os[i]) < size(os[j])) {                    swap(i, j);  // swapping indices is much faster than swapping ordered sets                }                for (const auto& x : os[j]) {  // each node is merged at most O(logn) times                    os[i].insert(x);  // each add costs O(logn)                }            };             vector<int> result(size(queries), -1);            vector<tuple<int, int, int>> stk = {{1, 0, 0}};            while (!empty(stk)) {                auto [step, u, curr] = stk.back(); stk.pop_back();                if (step == 1) {                    curr ^= vals[u];                    os[idxs[u]].insert(curr);                    stk.emplace_back(2, u, curr);                    for (const auto& v : adj[u]) {                        stk.emplace_back(1, v, curr);                    }                } else if (step == 2) {                    for (const auto& v : adj[u]) {                        small_to_large_merge(idxs[u], idxs[v]);                    }                    for (const auto& i : lookup[u]) {  // Total Time: O(qlogn)                        if (queries[i][1] - 1 < size(os[idxs[u]])) {                            result[i] = *(os[idxs[u]].find_by_order(queries[i][1] - 1));                        }                    }                }            }            return result;        };         return iter_dfs();    }}; // Time:  O(n * (logn)^2 + qlogn)// Space: O(n + q)#include <ext/pb_ds/assoc_container.hpp>#include <ext/pb_ds/tree_policy.hpp>using namespace __gnu_pbds;// dfs, small-to-large merging, ordered setclass Solution2 {public:    vector<int> kthSmallest(vector<int>& par, vector<int>& vals, vector<vector<int>>& queries) {        vector<vector<int>> adj(size(par));        for (int u = 0; u < size(par); ++u) {            const auto& p = par[u];            if (p != -1) {                adj[p].emplace_back(u);            }        }        vector<vector<int>> lookup(size(adj));        for (int i = 0; i < size(queries); ++i) {            lookup[queries[i][0]].emplace_back(i);        }        const auto& small_to_large_merge = [&](auto& ptr1, auto& ptr2) {  // Total Time: O(n * (logn)^2)            if (size(*ptr1) < size(*ptr2)) {                swap(ptr1, ptr2);  // swapping ptrs is much faster than swapping ordered sets            }            for (const auto& x : *ptr2) {  // each node is merged at most O(logn) times                ptr1->insert(x);  // each add costs O(logn)            }        };         vector<int> result(size(queries), -1);        using ordered_set = tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update>;        const function<unique_ptr<ordered_set> (int, int)> dfs = [&](int u, int curr) {            curr ^= vals[u];            auto ptr = make_unique<ordered_set>();            ptr->insert(curr);            for (const auto& v : adj[u]) {                auto new_ptr = dfs(v, curr);                small_to_large_merge(ptr, new_ptr);            }            for (const auto& i : lookup[u]) {  // Total Time: O(qlogn)                if (queries[i][1] - 1 < size(*ptr)) {                    result[i] = *(ptr->find_by_order(queries[i][1] - 1));                }            }            return ptr;        };         dfs(0, 0);        return result;    }}; 

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 ↗