DSA

Time Complexity & Big O Notation

brian | Published: March 12, 2024, 4:39 p.m. | Updated: May 25, 2025, 9:41 p.m.

Profile Picture

 

Time Complexity: A way of showing  how the run-time of a function increases as the size of the input increases

 

Big O Notation: It is a way of analyzing the run-time (the amount of time it takes for our algorithm to execute as the input size of our algorithm grows)

 

O (1): in Big O of 1(Also called Constant Time), even if we increase our input size, our time it takes will always stay the same.

*a computer can jump to any memory address in one step  O(1)

*Insertion at end: insertion at the end only takes one step  O (1)

*Deleting from the end only takes one step O (1)

Examples of O(1) in python usings lists

nums = [1, 2, 3, 4, 5]
print(nums[1])
nums.pop()

 

 

 

O (n): Here as our input size is increased, so is the amount of time it takes for our algorithm to execute (Time complexity Linear Time)

nums = [1, 2, 3, 4, 5]

answer = sum(nums)
print(answer)

Above, if we increase the amount if items in the list 'nums', the longer it would take to execute. For example, if I compared the amount of time it took with 4 items in the list, compared to 10 million, the list with 10 million would take longer to execute because we have to add every single number and 10 million is a much bigger number than 5 

 

*Insertion value at middle: first we have to shift all the right pieces  data to the right to make room, then finally when there is room we can insert
*worst case scenario is inserting in the beginning, because first we have to shift every single piece of data to the right to make room, then insert the value. O(n)

 

Searching Vs Reading


*reading vs searching... reading would be proividing the computer an index and asking it to return a value which is quick O (1)
*searching is providing the computer a value, and ask to return the index.. its longer because the computer has no way to jump to a particular value
*so for searching, the computer has to inspect one cell at a time []-[]-[]-[]-[]-[]  ----> O(n)