ProgrammingHard
A loop walks a string with for (i = 0; i < strlen(s); i++) on a string of length 10^6. What is the total cost?
- A. About 5 x 10^11 character reads, which is too slow for a one-second limit
- B. About 10^6 reads, which is fast enough
- C. About 10^9 reads, which is borderline
- D. Constant time, since strlen is cached
Correct answer: A. About 5 x 10^11 character reads, which is too slow for a one-second limit
strlen scans the string each time, so the loop costs about n^2 / 2 = 5 x 10^11 reads. Calling strlen once fixes it.
More C Programming questions
- A binary search on the answer in [1, 10^18] computes mid = (lo + hi) / 2 with long long. Is this safe?
- A sum of n = 10^5 terms is stored in a double. Is this a safe choice for exact integer sums up to 10^14?
- A loop reads n numbers and stores them in int a[n] as a VLA of size up to 10^6 inside main. What is the main risk?
- To sort 10^6 integers with qsort, which comparator is correct for all int values?
- A counting pass over an array of 10^7 values, each in [0, 9], uses 10 counters. Which statement is correct?
- Which output method is fast enough for 10^6 lines of output in C?