Approach

This problem is not really hard, the most complex part is to handle the edge removal.

Since for the leaf node, we always need to flip the edge connect to it, so we can do it first, and remove that edge and node from the tree. Iteratively doing this process until can’t flip.

The time and space complexity are both O(V+E). Originally I’m using the adjacency list traversal to check if the node is removed, and this is actually a sqaure-time solution, since the node might be like a star-like tree with many edge, and we many need to count multiple times for the node when approaching from different edge. Therefore, I modifed it to track the degree of each node, and this can be done in constant time.

Code

class Solution {
public:
    vector<int> minimumFlips(int n, vector<vector<int>>& edges, string start, string target) {
        if(n == 1) {
            if(start[0] == target[0]) return {};
            return {-1};
        }

        vector<int> degree(n, 0);
        vector<vector<pair<int, int>>> adj(n);
        for(int i = 0 ; i < edges.size() ; ++i) {
            adj[edges[i][0]].push_back({edges[i][1], i});
            adj[edges[i][1]].push_back({edges[i][0], i});
            ++degree[edges[i][1]];
            ++degree[edges[i][0]];
        }

        vector<int> ans;
        queue<int> q;
        vector<int> remove(n, false);
        for(int i = 0 ; i < n ; ++i) {
            if(degree[i] == 1) {
                q.push(i); // leaf idx
            }
        }

        while(!q.empty()) {
            int idx = q.front();
            q.pop();
            if(remove[idx] || degree[idx] > 1) continue;
            remove[idx] = true;
            bool flip = false;
            if(start[idx] != target[idx]) {
                start[idx] = (start[idx] == '1') ? '0' : '1';
                flip = true;
            }
            bool doFlip = false;
            for(const auto& [next, nextId]: adj[idx]) {
                if(remove[next]) continue;
                if(flip) {
                    doFlip = true;
                    ans.push_back(nextId);
                    start[next] = (start[next] == '1') ? '0' : '1';
                }
                --degree[next];
                q.push(next);
            }
            if(flip && !doFlip) return {-1};
        }
        sort(ans.begin(), ans.end());
        return ans;
    }
};