What are the key features of good code?
- Readable
- Scalable
- Managed time complexity (Big-O)
- Managed space complexity
There are different types of Big-O notations:
- O(n)
- O(1)
- O(n^2)
- O(2^n)
- O(n!)
- O(log n)
- O(n log n)
We will discusses about different notation of Big-O step by step.
When the algorithm has linear time complexity then it is called O(n)The number of operations will depend on the number of array elements.
Here is an example of O(1) time complexity.
const names = ['abc','def','xyz']
for(let i = 0; i < names.length; i++){
if(names[i] == 'xyz'){
console.log('Hello '+ names[i]);
}
}
If we look at the upper graph, the number of orations is dependent on the array of elements.
If n = 0, operations= 0
If n = 1, operations= 1
If n = 2, operations= 2
If n = 3, operations= 3
and so on
When time is constant to execute an algorithm then the time complexity of the algorithm is O(1)Here is an example of O(1) time complexity.
const names = ['abc','def','xyz'];
const namesObject = {
'abc': true,
'def': true,
'xyx': true
};
let elementExistInArray = !!namesObject['xyx']; // namesObject['xyx'] ? true : false;
console.log(elementExistInArray);