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?

  1. A. About 10^5, which is linear
  2. B. About 5 x 10^9, which is about n^2 / 2
  3. C. About 10^10, which is n^2
  4. 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

Exams that ask this topic