Time Complexity Practice Exercises
Time Complexity Practice Exercises
The time complexity of the function 'func' is O(n^2). This is due to the presence of nested loops, where each loop runs 'n' times. The outer loop runs 'n' times, and for each iteration of the outer loop, the inner loop also runs 'n' times, leading to n * n = n^2 total iterations, which determines the quadratic time complexity .
The complexities equivalent to O(N) are a) O(N + P), where P < N/9, and c) O(N + 8log N). Complexity a) remains O(N) because P grows slower than N and does not affect the leading term. In complexity c), the logarithmic component (8log N) grows much slower than the linear component, so it is also simplified to O(N). Complexities b) O(9N-k) and d) O(N + M^2) are not equivalent; the former due to constant factors and the latter because M^2 could grow larger than N .
The second 'isPrime' function has a time complexity of O(1), assuming the loop runs with a constant upper limit of 10000. Unlike traditional algorithms which check divisors up to √n, this loop is hard-coded to iterate up to √10000, a fixed value, independently of 'n'. Therefore, it does not scale with the input but rather checks divisibility within a predetermined range, unsuitable for large 'n' .
The average processing time T(6) can be determined by analyzing the recursive function. The recursion divides the problem into smaller subproblems split randomly, leading the function to call itself twice with different parameters based on 'i', a random integer less than 'n'. Solving this precisely requires probabilistic analysis, often done using recurrence relations. For T(n), the recurrence can be approximated by T(n) ≈ n log n, typical for recursive tree structures. However, calculating for T(6) specifically without more specific recursive relation analysis is complex, especially without defining random(n).
The time complexity of the function 'func1' is O(n). This is because it consists of two separate loops that each iterate over the entire array, resulting in a linear time complexity. The first loop calculates the sum of array elements, and the second loop calculates the product, both operating independently with O(n) complexity. Hence, the overall time complexity remains O(n).
The complexity of the given 'isPrime' function for checking if a number is prime is O(√n). This is because the loop iterates from 2 up to the square root of 'n'. For any non-prime number 'n', at least one factor will be less than or equal to √n, allowing detection of non-primality without inspecting the entire range, thereby improving efficiency to O(√n).
The runtime for summing values in a balanced binary search tree using this recursive function is O(n), where 'n' is the number of nodes in the tree. The function performs a recursive traversal that visits each node exactly once (depth-first search), hence processing every node leads to a linear time complexity .



