Union basics in C++ - Time & Space 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.
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 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.
Accessing or setting a union member takes the same time regardless of input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The time stays constant no matter how big the input is.
Time Complexity: O(1)
This means accessing or setting a union member takes the same amount of time no matter what.
[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.
Understanding that unions provide constant-time access helps you explain memory-efficient data handling clearly and confidently.
What if we added a loop to copy each character of the union's string member? How would the time complexity change?