ProgrammingVery hard
Growing a dynamic array by a fixed 1 element every time it fills (capacity + 1) costs what in the worst case for N pushes?
- A. About N copies in total, so pushes are O(1) each
- B. About N log N copies, like merge sort
- C. About N^2 / 2 element copies in total, so pushes are O(N) each on average
- D. About N copies only when the array is shrunk
Correct answer: C. About N^2 / 2 element copies in total, so pushes are O(N) each on average
Each growth copies the whole array, so the copies sum to 1 + 2 + ... + N, which is about N^2 / 2. Doubling avoids this.
More C Programming questions
- Which method is correct and fast enough for answering 10^5 range-sum queries on an array of 10^5 integers?
- Which method is correct and fast enough for n choose r modulo p = 10^9 + 7 for 10^6 queries with n up to 10^6?
- To compute the sum of 1 through n = 10^9 without overflow in C, which code is correct?
- Which method finds all primes up to 10^6 in time that is correct and fast enough?
- Binary search on the answer: a monotone check runs in O(n) and the answer lies in [1, 10^9]. What is the total complexity?
- A recursive naive Fibonacci fib(n) makes calls(n) = calls(n-1) + calls(n-2) + 1 with calls(0) = calls(1) = 1. Roughly how many calls does…