Bit Manipulation Basics AND OR XOR NOT Left Right Shift in DSA Python - Time & Space Complexity
Bit manipulation operations are very fast and work directly on the bits of numbers.
We want to understand how the time to perform these operations changes as the size of the input number grows.
Analyze the time complexity of the following bit manipulation operations.
# Example bit operations on integers
x = 42 # binary: 101010
y = 15 # binary: 001111
and_result = x & y # AND operation
or_result = x | y # OR operation
xor_result = x ^ y # XOR operation
not_result = ~x # NOT operation
left_shift = x << 2 # Left shift by 2 bits
right_shift = x >> 1 # Right shift by 1 bit
This code performs basic bitwise operations on two integers.
Each bitwise operation processes bits one by one internally.
- Primary operation: Bitwise AND, OR, XOR, NOT, and shifts.
- How many times: Once per bit of the input number.
The number of bits depends on the size of the number (n bits).
| Input Size (bits) | Approx. Operations |
|---|---|
| 10 | About 10 bit operations |
| 100 | About 100 bit operations |
| 1000 | About 1000 bit operations |
Pattern observation: The work grows linearly with the number of bits in the input.
Time Complexity: O(n)
This means the time to do bit operations grows linearly with the number of bits in the number.
[X] Wrong: "Bitwise operations always take constant time no matter the number size."
[OK] Correct: Actually, the time depends on how many bits the number has, so bigger numbers take proportionally more time.
Understanding bit manipulation time helps you write efficient code and explain performance clearly in interviews.
"What if we used fixed-size 32-bit integers instead of arbitrary large integers? How would the time complexity change?"