techStackGuru

Constant time complexity O(1)


time-complexity-constant-time-1

An algorithm with constant time complexity with order O(1) does not depend on the input size n. In general, algorithms with O(1) time complexity are highly efficient because they always execute in the same amount of time, regardless of the size of the input.

As an example, assume an algorithm returns the first element of an array. Regardless of the number of elements in the array, the time complexity will remain the same.

const numbers = [1, 2, 3, 4, 5];

function getValue() {
  return numbers[0];
}

console.log(getValue()); // 1 

Example: Constant Time: O(1)

Lets take an example of even and odd.

function checkNumber(n) { 
  return n % 2 ? 'Odd' : 'Even'; 
}

console.log(checkNumber(2)); //  Even 
console.log(checkNumber(3)); //  Odd 

Example: Constant Time: O(1)

There is only one instance of "Learning Time Complexity" printed on the screen in the below code. Therefore, the complexity of time is constant: O(1)

console.log("Learning Time Complexity")