Assume 0-based indexing, we can shift n too instead of 1 in the following tricks.
ith bit: n | (1 << i)ith bit: n & ~(1 << i)ith bit, check if ith bit is set or unset: if n & (1 << i) > 0 then set, else unsetith bit: n ^ (1 << i)n & (n - 1)n | (n + 1)n & ~(n - 1)if(n & 1) then odd, else evenn & (n - 1) will be 0 (falsely reports 0 as a power of 2). Use this instead: if (n && !(n & (n - 1)) == 0)x = x ^ y; y = x ^ y; x = x ^ y;str[i] ^= 32n & (d-1), so in place of (n % 4) we can write (n & 3).(x ^ y) < 0a ^ b = 0 only if a, b are equalnumber of set bits in A ^ B.2x + x + x/2 = (x << 1) + x + (x >> 1)8x - x = (x << 3) - x+ operator: xPlusOne = -(~x), since ~x = -(x+1) holds.single set bit having even number of 0s on its right sideDo 2's complement, & with original number, take log2(ANDresult) = log2(n & -n) + 1(x | y) & (~x | ~y)n % 4 values can be n, 1, n+1, 0]n << k | n >> (32-k) and Right = n >> k | n << (32-k)Operations on Range:
ans = [L - R] = [1 - R] ^ [1 - (L-1)]O(n), TLE on LC0 (shift out and shift back replacing it with 0s). TC = O(log n)n & (n-1) and this unsets the rightmost set bit and then AND operation on this position with any other number will yield 0 at this position in the final answer, so we keep doing this to form ans till ans > left (in the last iteration ans & left will happen as left = ans-1). TC = O(popcount(n))Forming two buckets trick:
Counting Bits trick: usually we can count set bits in log n time using Brian-Kernighan’s Algorithm, but if we need to count set bits for each number in range [0 - n] we can do so in O(n) time using DP as dp[i] = dp[i/2] + i%2 where dp[0] = 0 is the base case problem video
N shifting it rightwards by 1 (dividing by 2; halving) will either have equal set bits (if N is even) or 1 extra set bits (if N is odd) since shifting causes LSB to get lostEverything we do on a binary representation of a number is log n time, since a number’s binary representation can contain atmost n bits.
XOR Linked List is a memory efficient probabilistic data structure that’s basically like a DLL but only one address is stored per node rather than two i.e. prev and next.
The address that is stored on a given node is the XOR of prev and next: prev ^ next. We can store address of the prev visited node and do prev ^ (prev ^ next) to get the address of the next node (next).
For storing address in the first and last node, XOR its prev/next with 0. We’ll know when we’ve reached the last node when we get next node address as 0, or we can also maintain a tail pointer and compare with current node.
Advantages:
Disadvantages:
Usage: XOR linked lists are a cool theoretical data structure, but practically obsolete due to safety, maintainability, and compatibility concerns.