ProgrammingHard
An algorithm does O(n) work on each of the n levels of a recursion that removes one element per level. Which total is correct?
- A. O(n^2), since the per-level work sums to 1 + 2 + ... + n
- B. O(n), since each level is linear
- C. O(n log n), like merge sort
- D. O(2^n), like naive recursion
Correct answer: A. O(n^2), since the per-level work sums to 1 + 2 + ... + n
Summing the per-level costs gives a quadratic total. Merge sort halves the input each level, which gives n log n instead.
More C Programming questions
- A loop calls strlen(s) on a fixed string of length 10^4 once per character of the same string. How many characters are read in total?
- A function computes the sum of 1 to n by recursion with depth n. For n = 10^6, what is the main risk?
- A program increments a counter inside three nested loops, each running n = 100 times. How many increments occur?
- In a loop for (i = 0; i < n; i++) x = x 2 % m; with m = 1000000007 and x kept as long long, what is the cost?
- Which loop computes the number of trailing zeros of n in O(number of zeros) time for an unsigned n greater than zero?
- A loop with i starting at 1 and i = 2 until i > n runs how many times for n = 1000?