O(1) - Constant Time Complexity
Description: An operation that takes constant time, regardless of the input size
The running time of a constant-time algorithm does not depend on the
input size. A typical constant-time algorithm is a direct formula that
calculates the answer.
Example 1: Accessing an element in an array by its index.
No matter the size of the array, the getElementAtIndex
function will directly access the element in a single operation.
Example 2: Calculating sum of first N natural number.
The time complexity of this function sumOfNaturalNumber
is considered constant, denoted as (O(1))
.
This classification is based on the observation that the function performs a fixed number of operations regardless of the input size (n). Specifically, it executes a multiplication, an addition, and a division—three operations in total. Since the number of operations does not increase with (n), the time complexity is constant.
In the image above, the X-axis represents the size of the array, and the Y-axis represents the time it takes to access an element. As you can see, it always takes the same amount of time (1 operation), regardless of the array size.
Because it always takes the same amount of time, this operation has constant time complexity.