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