- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 77 lines of C++ from the credited upstream file subarrays-with-xor-at-least-k.cpp.
- The implementation visibly relies on sequence storage.
- 3 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
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 {6private:7 class Trie {8 public:9 Trie(int bit_length)10 : bit_length_(bit_length)11 , nodes_() {12 new_node();13 }14 15 void add(int num) {16 int curr = 0;17 for (int i = bit_length_ - 1; i >= 0; --i) {18 const auto& x = (num >> i) & 1;19 if (nodes_[curr][x] == -1) {20 nodes_[curr][x] = new_node();21 }22 curr = nodes_[curr][x];23 ++cnts_[curr];24 }25 }26 27 int query(int prefix, int k) {28 int result = 0, curr = 0;29 for (int i = bit_length_ - 1; i >= 0 && curr != -1; --i) {30 const auto& t = (k >> i) & 1;31 const auto& x = (prefix >> i) & 1;32 if (t == 0) {33 const auto& tmp = nodes_[curr][1 ^ x];34 if (tmp != -1) {35 result += cnts_[tmp];36 }37 }38 curr = nodes_[curr][t ^ x];39 }40 if (curr != -1) {41 result += cnts_[curr];42 }43 return result;44 }45 46 private:47 int new_node() {48 nodes_.push_back(array<int, 2>{-1, -1});49 cnts_.emplace_back(0);50 return size(nodes_) - 1;51 }52 53 const int bit_length_;54 vector<array<int, 2>> nodes_;55 vector<int> cnts_;56 };57 58public:59 long long countXorSubarrays(vector<int>& nums, int k) {60 const auto& bit_length = [](int x) {61 return (x ? std::__lg(x) : -1) + 1;62 };63 64 int64_t result = 0;65 int prefix = 0;66 const auto& mx = max({ranges::max(nums), k, 1});67 Trie trie(bit_length(mx));68 trie.add(prefix);69 for (const auto& x : nums) {70 prefix ^= x;71 result += trie.query(prefix, k);72 trie.add(prefix);73 }74 return result;75 }76};77