ProgrammingHard
For a char buffer of length 10^6 that is processed once, which loop is correct and fast enough?
- A. for (size_t i = 0, len = strlen(buf); i < len; i++) process(buf[i]);
- B. for (size_t i = 0; i < strlen(buf); i++) process(buf[i]);
- C. for (size_t i = 0; buf[i] != '\0'; i++) for (size_t j = 0; j < strlen(buf); j++) process(buf[i]);
- D. for (size_t i = 0; i < sizeof buf; i++) process(buf[i]);
Correct answer: A. for (size_t i = 0, len = strlen(buf); i < len; i++) process(buf[i]);
Computing the length once gives one O(n) pass. The in-loop strlen version is O(n^2). The sizeof version reads past the string, and the nested version is O(n^2) or worse.
More C Programming questions
- A matrix of 3000 x 3000 cells is read once and each cell is visited a constant number of times. Which complexity bound applies to the…
- A recursive merge sort on 10^6 elements makes how many comparisons, roughly?
- Which function call costs O(n) time per call and can be avoided by caching its result in a loop?
- A recurrence T(n) = 2 T(n/2) + n describes which algorithm, with which complexity?
- For a number n up to 10^18 read as a decimal string, what is the number of digits, computed with one pass?
- A program keeps a set of at most 10^5 ints and answers membership queries 10^5 times. Which structure is correct and fast enough?