0
0
C Sharp (C#)programming~5 mins

Flags attribute and bitwise enums in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Flags attribute and bitwise enums
O(1)
Understanding Time Complexity

When using flags and bitwise enums, we want to know how fast operations like checking or combining flags run.

We ask: How does the time to process flags grow as we add more flags?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

[Flags]
enum Permissions
{
    None = 0,
    Read = 1,
    Write = 2,
    Execute = 4,
    Delete = 8
}

Permissions userPerms = Permissions.Read | Permissions.Write;
bool canWrite = (userPerms & Permissions.Write) == Permissions.Write;

This code combines flags using bitwise OR and checks a flag using bitwise AND.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Bitwise AND and OR operations on integer values representing flags.
  • How many times: Each operation runs once per check or combination, no loops involved.
How Execution Grows With Input

Each flag is a bit in an integer. Checking or combining flags uses simple bit operations that take the same time no matter how many flags there are.

Input Size (number of flags)Approx. Operations
41 bitwise operation
101 bitwise operation
321 bitwise operation

Pattern observation: The time stays the same even if we add more flags because bitwise operations work on fixed-size integers.

Final Time Complexity

Time Complexity: O(1)

This means checking or combining flags takes the same short time no matter how many flags exist.

Common Mistake

[X] Wrong: "Checking multiple flags takes longer as we add more flags because we have to check each one separately."

[OK] Correct: Bitwise operations check all flags at once using a single operation, so time does not grow with more flags.

Interview Connect

Understanding how bitwise flags work and their constant-time checks shows you know efficient ways to handle multiple options compactly.

Self-Check

"What if we stored flags in a list instead of bits? How would the time complexity change?"