# O(1) Time Complexity:
# Accessing an element directly in an array/list by its index is a great example of constant time complexity:
my_list = [1, 2, 3, 4]
element = my_list[2]
# O(log n) Time Complexity:
# Binary search is an ideal example for logarithmic complexity:
def binary_search(arr, target):
low, high = 0, len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
# O(n) Time Complexity:
# A linear search through a list is the simplest example:
def linear_search(arr, target):
for index, value in enumerate(arr):
if value == target:
return index
return -1
# O(n²) Time Complexity:
# \Nested loops that iterate over a 2D matrix represent quadratic complexity:
def print_pairs(arr):
for i in range(len(arr)):
for j in range(len(arr)):
print(f"({arr[i]}, {arr[j]})")