Constant Time Complexity

Constant time complexity with example

In constant time complexity, the time required to execute an operation does not depend on the size of the input. No matter how large or small the input is, the operation will always take the same amount of time to complete. This is denoted by O(1).

Example

Let's look at a simple example in Python:

def get_first_element(my_list):
    return my_list[0]

Explanation

In this example:

  1. The function get_first_element takes a list as input and returns the first element.
  2. Accessing the first element of a list is a constant-time operation. It doesn’t matter if the list has 1 element or 1,000,000 elements – accessing the first element takes the same amount of time.
  3. Therefore, this function has O(1) time complexity.

Real-World Analogy

Imagine you have a big stack of papers, but you only want to grab the very first paper. Whether the stack has 5 or 500 pages, grabbing the first paper will always take the same amount of time.