#1516HardPremium on LC~50 min

Move Sub-Tree of N-Ary Tree

Time O(n) · Space O(h) · Official statement on LeetCode

cpppython

Solutions

// Time:  O(n)
// Space: O(h)

/*
// Definition for a Node.
class Node {
public:
    int val;
    vector<Node*> children;

    Node() {}

    Node(int _val) {
        val = _val;
    }

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/

// one pass solution without recursion
class Solution {
public:
    Node* moveSubTree(Node* root, Node* p, Node* q) {
        unordered_map<Node *, Node *> lookup;
        const auto& is_ancestor = iter_find_parents(root, nullptr, p, q, false, &lookup);
        if (lookup.count(p) && lookup[p] == q) {
            return root;
        }
        q->children.emplace_back(p);
        if (!is_ancestor) {
            lookup[p]->children.erase(find(begin(lookup[p]->children), end(lookup[p]->children), p));
        } else {
            lookup[q]->children.erase(find(begin(lookup[q]->children), end(lookup[q]->children), q));
            if (p == root) {
                root = q;
            } else {
                *find(begin(lookup[p]->children), end(lookup[p]->children), p) = q;
            }
        }
        return root;
    }

private:
    bool iter_find_parents(Node *node, Node *parent, Node *p, Node *q,
                           bool is_ancestor,
                           unordered_map<Node *, Node *> *lookup) {
        vector<tuple<int, Node *, Node *, bool, int>> stk = {tuple(1, node, parent, is_ancestor, -1)};
        while (!stk.empty()) {
            const auto [step, node, parent, is_ancestor, i] = stk.back(); stk.pop_back();
            if (step == 1) {
                if (node == p || node == q) {
                    (*lookup)[node] = parent;
                    if (lookup->size() == 2) {
                        return is_ancestor;
                    }
                }
                stk.emplace_back(2, node, parent, is_ancestor, node->children.size() - 1);
            } else {
                if (i < 0) {
                    continue;
                }
                stk.emplace_back(2, node, parent, is_ancestor, i - 1);
                stk.emplace_back(1, node->children[i], node, is_ancestor || node == p, -1);
            }
        }
        assert(false);
        return false;
    }
};

// Time:  O(n)
// Space: O(h)
// one pass solution with recursion
class Solution_Recu {
public:
    Node* moveSubTree(Node* root, Node* p, Node* q) {
        unordered_map<Node *, Node *> lookup;
        const auto& [_, is_ancestor] = find_parents(root, nullptr, p, q, false, &lookup);
        if (lookup.count(p) && lookup[p] == q) {
            return root;
        }
        q->children.emplace_back(p);
        if (!is_ancestor) {
            lookup[p]->children.erase(find(begin(lookup[p]->children), end(lookup[p]->children), p));
        } else {
            lookup[q]->children.erase(find(begin(lookup[q]->children), end(lookup[q]->children), q));
            if (p == root) {
                root = q;
            } else {
                *find(begin(lookup[p]->children), end(lookup[p]->children), p) = q;
            }
        }
        return root;
    }

private:
    pair<bool, bool> find_parents(Node *node, Node *parent, Node *p, Node *q,
                                  bool is_ancestor,
                                  unordered_map<Node *, Node *> *lookup) {
        if (node == p || node == q) {
            (*lookup)[node] = parent;
            if (lookup->size() == 2) {
                return {true, is_ancestor};
            }
        }
        for (const auto& child : node->children) {
            const auto& [found, result] = find_parents(child, node, p, q, is_ancestor || node == p, lookup);
            if (found) {
                return {true, result};
            }
        }
        return {false, false};
    }
};

// Time:  O(n)
// Space: O(h)
// two pass solution without recursion
class Solution2 {
public:
    Node* moveSubTree(Node* root, Node* p, Node* q) {
        unordered_map<Node *, Node *> lookup;
        iter_find_parents(root, nullptr, p, q, &lookup);
        if (lookup.count(p) && lookup[p] == q) {
            return root;
        }
        q->children.emplace_back(p);
        if (!iter_is_ancestor(p, q)) {
            lookup[p]->children.erase(find(begin(lookup[p]->children), end(lookup[p]->children), p));
        } else {
            lookup[q]->children.erase(find(begin(lookup[q]->children), end(lookup[q]->children), q));
            if (p == root) {
                root = q;
            } else {
                *find(begin(lookup[p]->children), end(lookup[p]->children), p) = q;
            }
        }
        return root;
    }

private:
    void iter_find_parents(Node *node, Node *parent, Node *p, Node *q,
                           unordered_map<Node *, Node *> *lookup) {
        vector<tuple<int, Node *, Node *, int>> stk = {tuple(1, node, parent, -1)};
        while (!stk.empty()) {
            const auto [step, node, parent, i] = stk.back(); stk.pop_back();
            if (step == 1) {
                if (node == p || node == q) {
                    (*lookup)[node] = parent;
                    if (lookup->size() == 2) {
                        return;
                    }
                }
                stk.emplace_back(2, node, parent, node->children.size() - 1);
            } else {
                if (i < 0) {
                    continue;
                }
                stk.emplace_back(2, node, parent, i - 1);
                stk.emplace_back(1, node->children[i], node, -1);
            }
        }
    }
    
    bool iter_is_ancestor(Node *node, Node *q) {
        vector<tuple<int, Node *, int>> stk = {tuple(1, node, -1)};
        while (!stk.empty()) {
            const auto [step, node, i] = stk.back(); stk.pop_back();
            if (step == 1) {
                stk.emplace_back(2, node, node->children.size() - 1);
            } else {
                if (i < 0) {
                    continue;
                }
                if (node->children[i] == q) {
                    return true;
                }
                stk.emplace_back(2, node, i - 1);
                stk.emplace_back(1, node->children[i], -1);
            }
        }
        return false;
    }
};

// Time:  O(n)
// Space: O(h)
// two pass solution with recursion
class Solution2_Recu {
public:
    Node* moveSubTree(Node* root, Node* p, Node* q) {
        unordered_map<Node *, Node *> lookup;
        find_parents(root, nullptr, p, q, &lookup);
        if (lookup.count(p) && lookup[p] == q) {
            return root;
        }
        q->children.emplace_back(p);
        if (!is_ancestor(p, q)) {
            lookup[p]->children.erase(find(begin(lookup[p]->children), end(lookup[p]->children), p));
        } else {
            lookup[q]->children.erase(find(begin(lookup[q]->children), end(lookup[q]->children), q));
            if (p == root) {
                root = q;
            } else {
                *find(begin(lookup[p]->children), end(lookup[p]->children), p) = q;
            }
        }
        return root;
    }

private:
    bool find_parents(Node *node, Node *parent, Node *p, Node *q, unordered_map<Node *, Node *> *lookup) {
        if (node == p || node == q) {
            (*lookup)[node] = parent;
            if (lookup->size() == 2) {
                return true;
            }
        }
        for (const auto& child : node->children) {
            if (find_parents(child, node, p, q, lookup)) {
                return true;
            }
        }
        return false;
    }

    bool is_ancestor(Node *node, Node *q) {
        for (const auto& child : node->children) {
            if (child == q || is_ancestor(child, q)) {
                return true;
            }
        }
        return false;
    }
};

Beginner Explanation

What is Move Sub-Tree of N-Ary Tree?

Move Sub-Tree of N-Ary Tree (LeetCode #1516) is a Hard problem that primarily trains tree.

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 dfs backtracking and stack.
  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: DFS, Stack.

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

Interview Walkthrough

Interview approach for Move Sub-Tree of N-Ary Tree

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 dfs backtracking and stack.

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 (O(n)) and space (O(h)) 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 O(n) time and O(h) space.

Pattern focus: dfs backtracking and stack

Use the pattern as a checklist:

  • dfs backtracking — confirm the invariant holds after each step
  • stack — 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 O(n)
Space O(h)

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 Move Sub-Tree of N-Ary Tree

  1. Skipping edge cases — empty collections, single-element inputs, max constraints.
  2. Wrong invariant for dfs backtracking and stack — 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 dfs backtracking and stack:

  • 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: tree.

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 Move Sub-Tree of N-Ary Tree in a second language (cpp, python).
  2. Drill 3–5 more problems tagged tree.
  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 Move Sub-Tree of N-Ary Tree: show input structure (tree), highlight the moving parts of the dfs backtracking and stack 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 dfs backtracking and stack 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

Move Sub-Tree of N-Ary Tree (#1516) — Hard. Pattern: dfs backtracking and stack. Complexity: O(n) time / O(h) space. Re-derive the invariant before coding.

FAQs

What is the time complexity of Move Sub-Tree of N-Ary Tree?+

The reference solutions aim for O(n) time and O(h) space. Always re-derive complexity from the code you write in the interview.

What pattern does Move Sub-Tree of N-Ary Tree use?+

It primarily maps to dfs backtracking and stack, within the broader topic of tree.

Is Move Sub-Tree of N-Ary Tree 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/move-sub-tree-of-n-ary-tree/