Problem solution · Python

Kth Smallest Path Xor Sum

Kth Smallest Path Xor Sum: a Python 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
96 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

  • 96 lines of Python from the credited upstream file kth-smallest-path-xor-sum.py.
  • The implementation visibly relies on sequence storage.
  • No explicit 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 · PythonPython
Use this to learn the idea, then write your own version.
# Time:  O(n * (logn)^2 + qlogn)# Space: O(n + q) from sortedcontainers import SortedList  # iterative dfs, small-to-large merging, sorted listclass Solution(object):    def kthSmallest(self, par, vals, queries):        """        :type par: List[int]        :type vals: List[int]        :type queries: List[List[int]]        :rtype: List[int]        """        def small_to_large_merge(sl1, sl2):  # Total Time: O(n * (logn)^2)            if len(sl1) < len(sl2):                sl1, sl2 = sl2, sl1            for x in sl2:  # each node is merged at most O(logn) times                if x not in sl1:                    sl1.add(x)  # each add costs O(logn)            return sl1         def iter_dfs():            sl = [SortedList() for _ in xrange(len(adj))]            result = [-1]*len(queries)            stk = [(1, (0, 0))]            while stk:                step, (u, curr) = stk.pop()                if step == 1:                    curr ^= vals[u]                    sl[u].add(curr)                    stk.append((2, (u, curr)))                    for v in reversed(adj[u]):                        stk.append((1, (v, curr)))                elif step == 2:                    for v in adj[u]:                        sl[u] = small_to_large_merge(sl[u], sl[v])                    for i in lookup[u]:  # Total Time: O(qlogn)                        if queries[i][1]-1 < len(sl[u]):                            result[i] = sl[u][queries[i][1]-1]            return result         adj = [[] for _ in xrange(len(par))]        for u, p in enumerate(par):            if p != -1:                adj[p].append(u)        lookup = [[] for _ in xrange(len(adj))]        for i, (u, _) in enumerate(queries):            lookup[u].append(i)        return iter_dfs()  # Time:  O(n * (logn)^2 + qlogn)# Space: O(n + q)from sortedcontainers import SortedList  # dfs, small-to-large merging, sorted listclass Solution2(object):    def kthSmallest(self, par, vals, queries):        """        :type par: List[int]        :type vals: List[int]        :type queries: List[List[int]]        :rtype: List[int]        """        def small_to_large_merge(sl1, sl2):  # Total Time: O(n * (logn)^2)            if len(sl1) < len(sl2):                sl1, sl2 = sl2, sl1            for x in sl2:  # each node is merged at most O(logn) times                if x not in sl1:                    sl1.add(x)  # each add costs O(logn)            return sl1         def dfs(u, curr):            curr ^= vals[u]            sl = SortedList([curr])            for v in adj[u]:                sl = small_to_large_merge(sl, dfs(v, curr))            for i in lookup[u]:  # Total Time: O(qlogn)                if queries[i][1]-1 < len(sl):                    result[i] = sl[queries[i][1]-1]            return sl         adj = [[] for _ in xrange(len(par))]        for u, p in enumerate(par):            if p != -1:                adj[p].append(u)        lookup = [[] for _ in xrange(len(adj))]        for i, (u, _) in enumerate(queries):            lookup[u].append(i)        result = [-1]*len(queries)        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 ↗