techStackGuru

Linear time complexity O(n)


time-complexity-linear-time-1

Linear time refers to an algorithms running time being proportional to the size of its inputs. As a result, if the input data size doubles, the algorithm will also double in running time.

Counting the instances of a particular element in an array can be viewed as an example of a linear time algorithm. Array elements are printed iteratively through the algorithm.

Example 1: Linear Time O(n)

Printing given array values.

function printNumbers(arr) {
    for (let i = 0; i < arr.length; i++) {
      console.log(arr[i]);
    }
}
  
const arr = [10, 20, 30, 40, 50];
printNumbers(arr); 
Output
10
20
30
40
50 

Example 2: Linear Time O(n)

Printing Hello 'n' number of times.

function printHello(n) {
    for (let i = 0; i < n; i++) {
      console.log("Hello");
    }
}
 
printHello(3); 
Output
Hello
Hello
Hello 

Example 3: Linear Time O(n)

Print Even or odd.

function printEven(arr) {
    for (let i = 0; i < arr.length; i++) {
    
    const res = arr[i] % 2 ? 'Odd' : 'Even'
    console.log(res);
    }
}
  
const arr = [10, 15, 20, 25];
printEven(arr); 
Output
Even
Odd
Even
Odd