0
0
DSA Pythonprogramming~5 mins

Check if Number is Even or Odd Using Bits in DSA Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Check if Number is Even or Odd Using Bits
O(1)
Understanding Time Complexity

We want to know how fast we can tell if a number is even or odd using bits.

How does the time to check change as the number gets bigger?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

def is_even(num: int) -> bool:
    return (num & 1) == 0

number = 42
print(is_even(number))  # True if even, False if odd

This code uses a bitwise AND to check the last bit of the number to decide if it is even or odd.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: A single bitwise AND operation.
  • How many times: Exactly once per function call.
How Execution Grows With Input

The operation always takes the same time no matter how big the number is.

Input Size (n)Approx. Operations
101
1001
10001

Pattern observation: The time does not grow with input size; it stays constant.

Final Time Complexity

Time Complexity: O(1)

This means the check takes the same small amount of time no matter how big the number is.

Common Mistake

[X] Wrong: "Checking bits takes longer for bigger numbers because they have more bits."

[OK] Correct: The operation only looks at the last bit, so it always takes the same time regardless of number size.

Interview Connect

Knowing this quick bit check shows you understand how computers work with numbers and can write very fast code.

Self-Check

"What if we checked multiple bits to find if a number is divisible by 4? How would the time complexity change?"