- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 73 lines of Python from the credited upstream file count-pairs-with-xor-in-a-range.py.
- The implementation visibly relies on sequence storage, hash lookup, cached states.
- No explicit loop blocks detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4import collections5 6 78class Solution(object):9 def countPairs(self, nums, low, high):10 """11 :type nums: List[int]12 :type low: int13 :type high: int14 :rtype: int15 """16 def count(nums, x):17 result = 018 dp = collections.Counter(nums)19 while x:20 if x&1:21 result += sum(dp[(x^1)^k]*dp[k] for k in dp.iterkeys())2 22 dp = collections.Counter({k>>1: dp[k]+dp[k^1] for k in dp.iterkeys()})23 x >>= 124 return result25 26 return count(nums, high+1)-count(nums, low)27 28 29303132class Trie(object):33 def __init__(self):34 self.__root = {}35 36 def insert(self, num):37 node = self.__root38 for i in reversed(xrange(32)):39 curr = (num>>i) & 140 if curr not in node:41 node[curr] = {"_count":0}42 node = node[curr]43 node["_count"] += 144 45 def query(self, num, limit):46 node, result = self.__root, 047 for i in reversed(xrange(32)):48 curr = (num>>i) & 149 bit = (limit>>i) & 150 if bit:51 if curr in node:52 result += node[0^curr]["_count"] 53 if bit^curr not in node:54 break55 node = node[bit^curr]56 return result57 58 59class Solution2(object):60 def countPairs(self, nums, low, high):61 """62 :type nums: List[int]63 :type low: int64 :type high: int65 :rtype: int66 """67 result = 068 trie = Trie()69 for x in nums:70 result += trie.query(x, high+1)-trie.query(x, low)71 trie.insert(x)72 return result73