ProgrammingHard
A loop appends one character to a string with strcat(s, "x") for n = 10^5 times. Each strcat calls strlen on the whole string first. What is the total number of characters scanned?
- A. About 10^5, which is linear
- B. About 5 x 10^9, which is about n^2 / 2
- C. About 10^10, which is n^2
- D. About 2 x 10^5 because of the doubling
Correct answer: B. About 5 x 10^9, which is about n^2 / 2
The i-th call scans i characters, so the sum is n(n - 1)/2 = 4999950000. Keeping a length variable makes each append O(1).
More C Programming questions
- for (i = 0; i < strlen(s); i++) process(s[i]); with a string of length 5. How many times is strlen called?
- Which C code is correct and fast enough for finding whether a sorted array a of n = 2 x 10^5 ints has two elements summing to t?
- For N = 10^6 integers in the range 0 to 10^6, which sorting method is correct and fast enough?
- A queue is needed for 10^5 operations on an array. Which dequeue is correct and fast enough?
- Growing a dynamic array by a fixed 1 element every time it fills (capacity + 1) costs what in the worst case for N pushes?
- Which method is correct and fast enough for answering 10^5 range-sum queries on an array of 10^5 integers?