0
0
Cprogramming~5 mins

Union basics - 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 the program's steps grow as data changes.

We want to see how the time to run code with unions changes when the input size changes.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


#include <stdio.h>

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

void printUnion(union Data d, int type) {
    if (type == 0) printf("%d\n", d.i);
    else if (type == 1) printf("%f\n", d.f);
    else printf("%s\n", d.str);
}

int main() {
    union Data data;
    data.i = 10;
    printUnion(data, 0);
    return 0;
}
    

This code defines a union with different types and prints one value based on a type indicator.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Single function call to print a union member.
  • How many times: Called once in this example.
How Execution Grows With Input

Since the code prints one value from the union, the steps do not increase with input size.

Input Size (n)Approx. Operations
10About 1 print operation
100Still about 1 print operation
1000Still about 1 print operation

Pattern observation: The number of steps stays the same no matter the input size.

Final Time Complexity

Time Complexity: O(1)

This means the program takes the same amount of time no matter how big the input is.

Common Mistake

[X] Wrong: "Accessing different union members takes more time as the union size grows."

[OK] Correct: Accessing any member of a union is a direct operation and does not depend on the size of the union or input.

Interview Connect

Understanding how unions work and their time behavior helps you explain memory use and efficiency clearly in interviews.

Self-Check

"What if we added a loop to print multiple union values? How would the time complexity change?"