Algorithm Time Complexity and Space Complexity

¡Supera tus tareas y exámenes ahora con Quizwiz!

What's the space and time complexity of this code? (Note: Definition is formatted: Space, Time) Ex.) O(1), O(n) int getFirstElement(const std::vector<int>& arr) { return arr[0]; }

O(1), O(1)

What's the space and time complexity of this code? (Note: Definition is formatted: Space, Time) Ex.) O(1), O(n) int increment(int n) { return n + 1; }

O(1), O(1)

What's the space and time complexity of this code? (Note: Definition is formatted: Space, Time) Ex.) O(1), O(n) (Hint) The formal name for this time complexity is: Logarithmic Time int binarySearch(const std::vector<int>& arr, int target) { int left = 0, right = arr.size() - 1; while (left <= right) { int mid = left + (right - left) / 2; if (arr[mid] == target) return mid; else if (arr[mid] < target) left = mid + 1; else right = mid - 1; } return -1; }

O(1), O(log n)

What's the space and time complexity of this code? (Note: Definition is formatted: Space, Time) Ex.) O(1), O(n) int sumArray(const std::vector<int>& arr) { int total = 0; for (int num : arr) { total += num; } return total; }

O(1), O(n)

What's the space and time complexity of this code? (Note: Definition is formatted: Space, Time) Ex.) O(1), O(n) (Hint) The formal name for this time complexity is: Quadratic Time This function uses a nested loop to sort the array, leading to quadratic time complexity, but uses a constant amount of space. void bubbleSort(std::vector<int>& arr) { int n = arr.size(); for (int i = 0; i < n; ++i) { for (int j = 0; j < n - i - 1; ++j) { if (arr[j] > arr[j + 1]) { std::swap(arr[j], arr[j + 1]); } } } }

O(1), O(n^2)

What's the space and time complexity of this code? (Note: Definition is formatted: Space, Time) Ex.) O(1), O(n) Note: This function generates all subsets of the array, leading to exponential time and space complexity. std::vector<std::vector<int>> allSubsets(const std::vector<int>& arr) { if (arr.empty()) return {{}}; std::vector<std::vector<int>> subsets = allSubsets(std::vector<int>(arr.begin() + 1, arr.end())); std::vector<std::vector<int>> result = subsets; for (const auto& subset : subsets) { std::vector<int> newSubset = {arr[0]}; newSubset.insert(newSubset.end(), subset.begin(), subset.end()); result.push_back(newSubset); } return result; }

O(2^n), O(2^n)

What's the space and time complexity of this code? (Note: Definition is formatted: Space, Time) Ex.) O(1), O(n) Note: Creating an adjacency list involves initializing a list for each vertex (V) and iterating over each edge (E). def create_adjacency_list(V, edges): adj_list = {i: [] for i in range(V)} for u, v in edges: adj_list[u].append(v) adj_list[v].append(u) # If the graph is undirected return adj_list

O(V + E), O(V + E)

What's the space and time complexity of this code? (Note: Definition is formatted: Space, Time) Ex.) O(1), O(n) Note: BFS also visits each vertex (V) and edge (E) once. The space complexity is linear due to the visited set and queue. And remember that 2 * linear time is just linear time because they're close enough for the factor to not make a difference. from collections import deque def bfs(graph, start): visited = set() queue = deque([start]) while queue: vertex = queue.popleft() if vertex not in visited: visited.add(vertex) queue.extend(set(graph[vertex]) - visited) return visited

O(V), O(V + E)

What's the space and time complexity of this code? (Note: Definition is formatted: Space, Time) Ex.) O(1), O(n) Note: DFS visits each vertex (V) and edge (E) once. The space complexity is linear due to the recursion stack and visited set. And remember that 2 * linear time is just linear time because they're close enough for the factor to not make a difference. def dfs(graph, start, visited=None): if visited is None: visited = set() visited.add(start) for neighbor in graph[start]: if neighbor not in visited: dfs(graph, neighbor, visited) return visited

O(V), O(V + E)

What's the space and time complexity of this code? (Note: Definition is formatted: Space, Time) Ex.) O(1), O(n) Note: The recursion depth is logarithmic in relation to n because n/2 minimizes the n over TIME by halving it, therefore minimizing the number of function calls AND stack MEMORY used. int recursiveLog(int n) { if (n <= 1) return 0; else return 1 + recursiveLog(n / 2); }

O(log n), O(log n)

What's the space and time complexity of this code? (Note: Definition is formatted: Space, Time) Ex.) O(1), O(n) Note: The recursion depth is logarithmic and each level of recursion uses O(n) space for merging, leading to O(n log n) space complexity. void auxSpaceLogarithmic(std::vector<int>& arr, int left, int right) { if (left < right) { int mid = left + (right - left) / 2; auxSpaceLogarithmic(arr, left, mid); auxSpaceLogarithmic(arr, mid + 1, right); merge(arr, left, mid, right); } }

O(n log n), O(n log n)

What's the space and time complexity of this code? (Note: Definition is formatted: Space, Time) Ex.) O(1), O(n) (Hint) The formal name for this time complexity is: Factorial Time This function generates all permutations of the array, leading to factorial time and space complexity. std::vector<std::vector<int>> permutations(std::vector<int> arr) { if (arr.empty()) return {{}}; std::vector<std::vector<int>> result; for (int i = 0; i < arr.size(); ++i) { std::vector<int> rest(arr.begin(), arr.end()); rest.erase(rest.begin() + i); for (auto& perm : permutations(rest)) { perm.insert(perm.begin(), arr[i]); result.push_back(perm); } } return result; }

O(n!), O(n!)

What's the space and time complexity of this code? (Note: Definition is formatted: Space, Time) Ex.) O(1), O(n) Note: This function's recursive calls create space complexity that grows factorially, leading to an also factorial time complexity std::vector<std::vector<int>> factorialSpace(int n) { if (n == 0) return {{}}; std::vector<std::vector<int>> result; for (int i = 0; i < n; ++i) { auto subresults = factorialSpace(n - 1); result.insert(result.end(), subresults.begin(), subresults.end()); } return result; }

O(n!), O(n!)

What's the space and time complexity of this code? (Note: Definition is formatted: Space, Time) Ex.) O(1), O(n) (Hint) The formal name for this time complexity is: Exponential Time This recursive function calculates Fibonacci numbers, leading to exponential time complexity due to overlapping subproblems. Remember the call stack/stack is linear space complexity by default, and recursive functions use the call stack. int fibonacci(int n) { if (n <= 1) return n; return fibonacci(n - 1) + fibonacci(n - 2); }

O(n), O(2^n)

What's the space and time complexity of this code? (Note: Definition is formatted: Space, Time) Ex.) O(1), O(n) (Hint) The formal name for this time complexity is: Linearithmic Time This sorting algorithm (Merge Sort) divides the array in half log n times and performs linear work at each level. def merge_sort(arr): if len(arr) <= 1: return arr mid = len(arr) // 2 left = merge_sort(arr[:mid]) right = merge_sort(arr[mid:]) return merge(left, right) def merge(left, right): result = [] while left and right: if left[0] <= right[0]: result.append(left.pop(0)) else: result.append(right.pop(0)) result.extend(left or right) return result

O(n), O(n log n)

What's the space and time complexity of this code? (Note: Definition is formatted: Space, Time) Ex.) O(1), O(n) std::vector<int> createList(int n) { std::vector<int> result(n); for (int i = 0; i < n; ++i) { result[i] = i; } return result; }

O(n), O(n)

What's the space and time complexity of this code? (Note: Definition is formatted: Space, Time) Ex.) O(1), O(n) (Hint) The formal name for this time complexity is: Cubic Time This function uses three nested loops to multiply two matrices, leading to cubic time complexity std::vector<std::vector<int>> matrixMultiplication(const std::vector<std::vector<int>>& A, const std::vector<std::vector<int>>& B) { int n = A.size(); std::vector<std::vector<int>> result(n, std::vector<int>(n, 0)); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { for (int k = 0; k < n; ++k) { result[i][j] += A[i][k] * B[k][j]; } } } return result; }

O(n), O(n^3)

What's the space and time complexity of this code? (Note: Definition is formatted: Space, Time) Ex.) O(1), O(n) Note: This function creates an n x n matrix std::vector<std::vector<int>> createMatrix(int n) { return std::vector<std::vector<int>>(n, std::vector<int>(n, 0)); }

O(n^2), O(n^2)

What's the space and time complexity of this code? (Note: Definition is formatted: Space, Time) Ex.) O(1), O(n) Note: This function creates a 3-dimensional n x n x n matrix std::vector<std::vector<std::vector<int>>> create3DMatrix(int n) { return std::vector<std::vector<std::vector<int>>>(n, std::vector<std::vector<int>>(n, std::vector<int>(n, 0))); }

O(n^3), O(n^3)

What's the space and time complexity of this code? (Note: Definition is formatted: Space, Time) Ex.) O(1), O(n) Note: Creating an adjacency matrix (connection matrix) requires iterating over each vertex pair, thus creating a 2D / square matrix representing all of the different connections between the vertices in the graph in question. Javascript: function createAdjacencyMatrix(V) { let matrix = []; for (let i = 0; i < V; i++) { let row = new Array(V).fill(0); matrix.push(row); } return matrix; } Python: def create_adjacency_matrix(V): return [[0] * V for _ in range(V)]

O(v^2), O(v^2)


Conjuntos de estudio relacionados

N203 Psych midterm (first 147 Q's)/Final practice quiz

View Set

Ch. 11 Quiz: Project Risk Management

View Set

Chapter 61: Management of Patients with Dermatologic Disorders

View Set

Anthropology Exam 3 Quiz Questions

View Set

Chapter 20: Accounting Changes and Error Corrections

View Set

CE Direct hypertensive disorders of pregnancy

View Set

(Mc Graw Hill)Cell Nutrition Ch. 4, 6, 7

View Set

Security+ SY0-601 Domain 1: Attacks, Threats, and Vulnerabilities

View Set

ch 7-Membrane Structure and Function

View Set