3.1 Tasks with Constant Complexity O(1).
Accessing an array element by index:
Accessing an element in an array by its index is done in constant time, because the element's address is calculated directly.
def get_element(arr, index):
return arr[index]
Inserting an element at the start of a list (Deque):
Using a double-ended queue (deque) allows inserting an element at the start of a list in constant time.
from collections import deque
def insert_element(dq, element):
dq.appendleft(element)
3.2 Tasks with Linear Complexity O(n).
Linear search in an array:
Searching for an element in an unsorted array is done in linear time because you might need to check each element.
def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i
return -1
Counting the number of elements in an array:
Traversing all elements in an array to count them takes linear time.
def count_elements(arr):
count = 0
for element in arr:
count += 1
return count
3.3 Tasks with Logarithmic Complexity O(log n).
Binary search:
Searching for an element in a sorted array using binary search is done in logarithmic time.
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
Inserting an element in a binary search tree:
Inserting an element into a balanced binary search tree (BST) takes logarithmic time.
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def insert(root, key):
if root is None:
return Node(key)
if key < root.val:
root.left = insert(root.left, key)
else:
root.right = insert(root.right, key)
return root
3.4 Tasks with Quadratic Complexity O(n^2).
Bubble sort:
Sorting an array using bubble sort is quadratic in time.
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
Checking for duplicates using a double loop:
Checking an array for duplicates using a double loop takes quadratic time.
def has_duplicates(arr):
n = len(arr)
for i in range(n):
for j in range(i + 1, n):
if arr[i] == arr[j]:
return True
return False
3.5 Tasks with Exponential Complexity O(2^n).
Tower of Hanoi problem:
Solving the Tower of Hanoi problem takes exponential time due to the need to move each disk.
def hanoi(n, source, target, auxiliary):
if n == 1:
print(f"Move disk 1 from {source} to {target}")
return
hanoi(n - 1, source, auxiliary, target)
print(f"Move disk {n} from {source} to {target}")
hanoi(n - 1, auxiliary, target, source)
Generating all subsets of a set:
Generating all subsets of a set takes exponential time since each subset must be considered.
def generate_subsets(s):
result = []
subset = []
def backtrack(index):
if index == len(s):
result.append(subset[:])
return
subset.append(s[index])
backtrack(index + 1)
subset.pop()
backtrack(index + 1)
backtrack(0)
return result
print(generate_subsets([1, 2, 3]))
GO TO FULL VERSION