3.7.20 · D3 · HinglishAlgorithm Paradigms

Worked examplesBit manipulation — XOR tricks, LSB, counting set bits

3,049 words14 min read↑ Read in English

3.7.20 · D3 · Coding › Algorithm Paradigms › Bit manipulation — XOR tricks, LSB, counting set bits


The scenario matrix

Is topic ka har problem inhi cells mein se kisi ek mein aata hai. Hum har ek ke liye ek worked example dete hain.

Cell Kya toot-ta hai / kya test hota hai Covered by
A. XOR-pairs, positive ints basic "sab do baar, ek odd" wala Example 1
B. XOR range, missing element indices ke saath XOR karo Example 2
C. XOR splits into two uniques ek XOR pass kaafi nahi — ek split bit chahiye Example 3
D. x & -x on a positive int lowest set bit isolate karo Example 4
E. x & -x on a NEGATIVE int two's complement ka two's complement Example 5
F. Zero / degenerate input x = 0, single-element array, powers of two Example 6
G. popcount, dense vs sparse naive vs Kernighan loop counts Example 7
H. The "thrice except one" twist XOR fail ho jaata hai — mod-3 bit counting Example 8
I. Word problem (real world) toggling / parity real life mein Example 9
J. Exam trap negatives par right-shift, aliased swap Example 10

Prerequisites jo tumhare paas open ho sakti hain: Two's Complement Representation, Logarithms and Powers of Two, Hash Sets vs O(1)-space tricks.


Cell A — XOR pairs, positive integers


Cell B — missing element in a full range


Cell C — two unique numbers (the split-bit trick)


Cell D — x & -x on a positive integer


Cell E — x & -x on a NEGATIVE integer


Cell F — zero aur degenerate inputs


Cell G — popcount: dense vs sparse loop counts


Cell H — "thrice except one" twist (XOR YAHAN FAIL KARTA HAI)


Cell I — ek real-world word problem


Cell J — exam trap


Recall Har cell ka ek-line summary

Duplicate parity → XOR (cells A,B,I). Do loners → XOR phir differing bit par split (C). Lowest set bit → x & -x, sign-independent (D,E). aur single elements guard karo (F). Sparse popcount → Kernighan (G). Triples → mod-3 bit tally, XOR galat hai (H). Negatives ki taraf shift karte hain aur aliased swaps self-destruct karte hain (J).

Connections

  • Bit manipulation — XOR tricks, LSB, counting set bits (index 3.7.20) — parent topic.
  • Two's Complement Representation — Examples 5 aur 10.
  • Hash Sets vs O(1)-space tricks — Example 8 ka memory wala alternative.
  • Logarithms and Powers of Two — Example 6 mein power-of-two test.
  • Bitmask Dynamic Programming — subsets-as-integers, Example 9 ko extend karta hai.
  • Greedy and Divide-and-Conquer — Example 3 ka split-bit idea.