0
0
C++programming~5 mins

Union basics in C++ - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Union basics
O(1)
Understanding Time Complexity

When working with unions in C++, it's helpful to understand how operations on them scale as data changes.

We want to see how the time to access or modify union members grows with input size.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


union Data {
    int i;
    float f;
    char str[20];
};

void setInt(Data &d, int value) {
    d.i = value;
}

int getInt(const Data &d) {
    return d.i;
}
    

This code defines a union with different types and functions to set and get an integer value.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Direct assignment and access of union members.
  • How many times: Each operation happens once per function call, no loops or recursion.
How Execution Grows With Input

Accessing or setting a union member takes the same time regardless of input size.

Input Size (n)Approx. Operations
101
1001
10001

Pattern observation: The time stays constant no matter how big the input is.

Final Time Complexity

Time Complexity: O(1)

This means accessing or setting a union member takes the same amount of time no matter what.

Common Mistake

[X] Wrong: "Accessing different union members takes longer as the union grows."

[OK] Correct: A union shares memory for all members, so accessing any member is a simple direct operation that does not depend on union size.

Interview Connect

Understanding that unions provide constant-time access helps you explain memory-efficient data handling clearly and confidently.

Self-Check

What if we added a loop to copy each character of the union's string member? How would the time complexity change?