ProgrammingModerate
Which function call costs O(n) time per call and can be avoided by caching its result in a loop?
- A. The 'sizeof' operator applied to an array
- B. A call to free on a single pointer
- C. Integer addition with +
- D. strlen(s) inside a loop condition over a string of length n
Correct answer: D. strlen(s) inside a loop condition over a string of length n
strlen has to scan the string each time it is called, so putting it in the loop condition repeats that scan. sizeof is a compile-time constant and free on one pointer is O(1) in typical use.
More C Programming questions
- 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?
- Which statement about finding the length of a null-terminated C string is correct?
- Which code gives the correct sum of the first n squares, for n up to 10^6, using a closed form in O(1)?
- Which operation on a dynamic array of n elements has O(1) amortised cost when using doubling?