Posts

Showing posts with the label Bitwise

Maximum Strong Pair XOR II - Bitwise Trie [JS]

Description   Solution: Bitwise Trie & Two Pointers Sort nums in asc order. For each  nums[i] , move up index  j  while  nums[j] - nums[i] <= nums[i] . Use a bitwise trie to find the maximum bitwise XOR, which is a greedy strategy of taking the opposite bit whenever possible. n = length of nums ,  m = max(nums[i]) Time Complexity:  O(n log(m)) Space Complexity:  O(m) var maximumStrongPairXor = function ( nums ) { nums.sort( ( a, b ) => a - b); let n = nums.length, trie = new BitwiseTrie(), maxXor = 0 ; for ( let i = 0 , j = 0 ; i < n; i++) { if (i > 0 ) trie.removeNum(nums[i - 1 ]); while (j < n && nums[j] - nums[i] <= nums[i]) { trie.addNum(nums[j]); j++; } maxXor = Math .max(maxXor, trie.maxXor(nums[i])); } return maxXor; }; class TrieNode { constructor ( ) { this .children = Array ( 2 ); this .num = null ; this .count = 0 ; } } class BitwiseTrie ...

Apply Bitwise Operations to Make Strings Equal - 4 Observations [JS]

Description   Solution: 4 Observations Outcomes of the 4 different situations: 11 -> 10 10 -> 11 01 -> 11 00 -> 00 Observations: If  s  only has  "0" s and target has a  "1" , it is impossible because we can never get a  "1"  from  "0" s. No matter how many  "1" s we try to remove, there will always be one left because  11 -> 10 . Therefore if  s  has  "1" s and target has only  "0" s, it is impossible. As long as we have at least one  "1" , we can produce as many or at little  "1" s as we like (must be more than  0 ). Getting more  "1" s:  01 -> 11 ,  10 -> 11 . Getting less  "1" s:  11 -> 10 , and  11 -> 01  if we flip the order of  (i, j) . Notice there is a cycle ( 11 -> 10 ,  10 -> 11 ). Because the order of  (i, j)  doesn't matter, this cycle applies for the opposite direction also. This means we can swap the o...