Find minimum swaps required to convert a Binary tree into BST

Pattern: Tree DP basics

medium

The tree is given as an array of a complete binary tree. A BST's inorder is sorted, and swapping values does not change the shape, so the answer is the fewest swaps to sort the inorder sequence: the sum over cycles of (cycle length - 1).

The problem

A complete binary tree is given as an array (children of index i at 2i + 1 and 2i + 2); values are distinct. Return the fewest swaps of two values that turn it into a binary search tree. [5, 6, 7, 8, 9, 10, 11] gives 3. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.

Think first

  • What does a BST's inorder look like?
  • Do swaps change the shape?
  • How many swaps does it take to sort a sequence of distinct values?

Hints

    Brute force, and why it fails

    Breadth-first search over swaps: exponential, only for tiny trees. The tests use it for small cases.

    The key insight

    The problem reduces to sorting the inorder with swaps, and the cycle count gives that minimum directly.

    Dry run

    80 
    61 
    92 
    53 
    104 
    75 
    116 

    arr = [5, 6, 7, 8, 9, 10, 11] (children of i at 2i + 1, 2i + 2). Inorder: 8, 6, 9, 5, 10, 7, 11.

    Step 1 of 3

    The plan

    order = inorder of the array tree
    idx = indexes of order sorted by value
    for each unvisited i: walk the cycle i -> idx[i] -> ...; swaps += length - 1
    

    Complexity

    Time
    O(n log n)
    Space
    O(n)

    Sorting the indexes dominates.

    Edge cases

    • Already a BST: 0.
    • One value.
    • Two values swapped: 1.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int minSwaps(int[] arr) {
            List<Integer> order = new ArrayList<>();
            inorder(arr, 0, order);                 // a BST's inorder must be sorted
            int n = order.size();
            Integer[] idx = new Integer[n];
            for (int i = 0; i < n; i++) idx[i] = i;
            Arrays.sort(idx, (a, b) -> Integer.compare(order.get(a), order.get(b)));   // where each sorted value is now
            boolean[] seen = new boolean[n];
            int swaps = 0;
            for (int i = 0; i < n; i++) {           // a cycle of length L needs L - 1 swaps
                int len = 0;
                for (int j = i; !seen[j]; j = idx[j]) { seen[j] = true; len++; }
                if (len > 0) swaps += len - 1;
            }
            return swaps;
        }
    
        private void inorder(int[] arr, int i, List<Integer> out) {   // children of i are 2i + 1 and 2i + 2
            if (i >= arr.length) return;
            inorder(arr, 2 * i + 1, out);
            out.add(arr[i]);
            inorder(arr, 2 * i + 2, out);
        }
    }

    C++

    class Solution {
    public:
        int minSwaps(vector<int>& arr) {
            vector<int> order;
            inorder(arr, 0, order);                 // a BST's inorder must be sorted
            int n = static_cast<int>(order.size());
            vector<int> idx(n);
            for (int i = 0; i < n; i++) idx[i] = i;
            sort(idx.begin(), idx.end(), [&](int a, int b) { return order[a] < order[b]; });   // where each sorted value is
            vector<bool> seen(n, false);
            int swaps = 0;
            for (int i = 0; i < n; i++) {           // a cycle of length L needs L - 1 swaps
                int len = 0;
                for (int j = i; !seen[j]; j = idx[j]) { seen[j] = true; len++; }
                if (len > 0) swaps += len - 1;
            }
            return swaps;
        }
    
        void inorder(vector<int>& arr, int i, vector<int>& out) {   // children of i are 2i + 1 and 2i + 2
            if (i >= static_cast<int>(arr.size())) return;
            inorder(arr, 2 * i + 1, out);
            out.push_back(arr[i]);
            inorder(arr, 2 * i + 2, out);
        }
    };

    Python

    class Solution:
        def minSwaps(self, arr: list[int]) -> int:
            order = []
    
            def inorder(i):                         # children of i are 2i + 1 and 2i + 2
                if i < len(arr):
                    inorder(2 * i + 1)
                    order.append(arr[i])
                    inorder(2 * i + 2)
    
            inorder(0)                              # a BST's inorder must be sorted
            idx = sorted(range(len(order)), key=lambda i: order[i])   # where each sorted value is now
            seen, swaps = [False] * len(order), 0
            for i in range(len(order)):             # a cycle of length L needs L - 1 swaps
                length, j = 0, i
                while not seen[j]:
                    seen[j] = True
                    j = idx[j]
                    length += 1
                swaps += max(0, length - 1)
            return swaps

    Common mistakes

    • Sorting the level order instead of the inorder.
    • Counting cycle lengths instead of length minus 1.

    Similar problems