- 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
- 55 lines of C++ from the credited upstream file 1803.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.
1struct TrieNode {2 vector<shared_ptr<TrieNode>> children;3 int count = 0;4 TrieNode() : children(2) {}5};6 7class Solution {8 public:9 int countPairs(vector<int>& nums, int low, int high) {10 int ans = 0;11 12 for (const int num : nums) {13 ans += getCount(num, high + 1) - getCount(num, low);14 insert(num);15 }16 17 return ans;18 }19 20 private:21 static constexpr int kHeight = 14;22 shared_ptr<TrieNode> root = make_shared<TrieNode>();23 24 void insert(int num) {25 shared_ptr<TrieNode> node = root;26 for (int i = kHeight; i >= 0; --i) {27 const int bit = num >> i & 1;28 if (node->children[bit] == nullptr)29 node->children[bit] = make_shared<TrieNode>();30 node = node->children[bit];31 ++node->count;32 }33 }34 35 36 int getCount(int num, int limit) {37 int count = 0;38 shared_ptr<TrieNode> node = root;39 for (int i = kHeight; i >= 0; --i) {40 const int bit = num >> i & 1;41 const int bitLimit = limit >> i & 1;42 if (bitLimit == 1) {43 if (node->children[bit] != nullptr)44 count += node->children[bit]->count;45 node = node->children[bit ^ 1];46 } else {47 node = node->children[bit];48 }49 if (node == nullptr)50 break;51 }52 return count;53 }54};55