0
0
DSA Pythonprogramming~5 mins

Bit Manipulation Basics AND OR XOR NOT Left Right Shift in DSA Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Bit Manipulation Basics AND OR XOR NOT Left Right Shift
O(n)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

The number of bits depends on the size of the number (n bits).

Input Size (bits)Approx. Operations
10About 10 bit operations
100About 100 bit operations
1000About 1000 bit operations

Pattern observation: The work grows linearly with the number of bits in the input.

Final Time Complexity

Time Complexity: O(n)

This means the time to do bit operations grows linearly with the number of bits in the number.

Common Mistake

[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.

Interview Connect

Understanding bit manipulation time helps you write efficient code and explain performance clearly in interviews.

Self-Check

"What if we used fixed-size 32-bit integers instead of arbitrary large integers? How would the time complexity change?"