DSA-Introduction: Part 5

Let’s start with an example of constant time complexity

C++ Code Example: Constant Time

#include <iostream>
using namespace std;

int main() {
    int x, y, z;         // Step 1: Variable declaration
    z = x + y;           // Step 2: Addition operation
    cout << z << endl;   // Step 3: Output the result
    return 0;            // Step 4: Exit the program
}

Assumption:

Let’s assume each operation takes 1 second.

Line of CodeDescriptionTime Taken
int x, y, z;Declaring 3 variables3 sec
z = x + y;Adding x and y, storing in z2 sec
cout << z;Printing result1 sec
return 0;Exiting program1 sec
Total7 sec

Why is this Constant Time (O(1))?

  • This program always takes the same number of steps, no matter what values x and y are.

  • Whether x = 1 or x = 1000000, the number of operations doesn't change.

So its time complexity is constant:

O(1), Ω(1), Θ(1)


For Beginners:

Think of it like this:

If you go to a vending machine and press a button, it always gives you the item in 1 step, no matter how big or small the snack is.

That’s constant time — always the same effort.

Constant Time Example 2

C++ Code

int main()
{
    int a, b, c, d, e, f;        // Variable declarations
    a = b + c + d;               // 2 additions + 1 assignment
    f = 2 * a - c * d;           // 2 multiplications + 1 subtraction + 1 assignment
    cout << a << b << c;        // Printing 3 variables
    return 0;                    // Exit
}

Updated Time Complexity Table

Line of CodeExplanationTime Taken
int a, b, c, d, e, f;Declare 6 variables6 sec
a = b + c + d;2 additions + 1 assignment3 sec
f = 2 * a - c * d;2 multiplications + 1 subtraction + 1 assignment4 sec
cout << a << b << c;Print 3 variables3 sec
return 0;Exit the program1 sec
Total Time17 sec

Time Complexity

  • Regardless of how large the variables are, the number of operations stays the same.

  • So this program still has:
    O(1) – Constant Time
    Ω(1) – Best Case
    Θ(1) – Average Case


Missed the earlier parts?
Make sure to check out the previous posts in this series for a complete understanding of time complexity and algorithm analysis:

1
Subscribe to my newsletter

Read articles from CHIRANJEEVI DRONAMRAJU directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

CHIRANJEEVI DRONAMRAJU
CHIRANJEEVI DRONAMRAJU