Approach
Breadth-first search
For Minimum Removals to Achieve Target Xor, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 59 lines of C++ from the credited upstream file minimum-removals-to-achieve-target-xor.cpp.
- The implementation visibly relies on sequence storage, hash lookup, cached states.
- 6 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution {6public:7 int minRemovals(vector<int>& nums, int target) {8 const auto& bfs = [&]() {9 unordered_map<int, int> dist;10 dist[0] = 0;11 vector<int> q = {0};12 while (!empty(q)) {13 vector<int> new_q;14 for (const auto& k : q) {15 if (k == target) {16 return dist[k];17 }18 for (const auto& x : nums) {19 if (dist.count(k ^ x)) {20 continue;21 }22 dist[k ^ x] = dist[k] + 1;23 new_q.emplace_back(k ^ x);24 }25 }26 q = move(new_q);27 }28 return -1;29 };30 31 for (const auto& x : nums) {32 target ^= x;33 }34 return bfs();35 }36};37 38394041class Solution2 {42public:43 int minRemovals(vector<int>& nums, int target) {44 unordered_map<int, int> dp;45 dp[0] = 0;46 for (const auto& x : nums) {47 target ^= x;48 unordered_map<int, int> new_dp(dp);49 for (const auto& [k, _] : dp) {50 if (!new_dp.count(k ^ x) || new_dp[k ^ x] > dp[k] + 1) {51 new_dp[k ^ x] = dp[k] + 1;52 }53 }54 dp = move(new_dp);55 }56 return dp.count(target) ? dp[target] : -1;57 }58};59