ProgrammingHard
For a string s of length up to 2 x 10^5 stored in a char array, which in-place reversal is correct and fast enough?
- A. int n = strlen(s); for (int i = 0; i < n / 2; i++) swap(&s[i], &s[strlen(s) - 1 - i]);
- B. for (int i = 0; i < strlen(s); i++) swap(&s[i], &s[strlen(s) - 1 - i]);
- C. int n = strlen(s); for (int i = 0, j = n - 1; i < j; i++, j--) swap(&s[i], &s[j]);
- D. for (int i = 0; s[i]; i++) s[i] = s[strlen(s) - i];
Correct answer: C. int n = strlen(s); for (int i = 0, j = n - 1; i < j; i++, j--) swap(&s[i], &s[j]);
Computing the length once keeps the loop linear. Calling strlen inside the loop costs O(n) each time, which gives about 10^10 work for this input. The other versions swap twice, or write past the end.
More C Programming questions
- What is the value of sizeof("hello") in C?
- char buf[] = "abcn"; buf[strcspn(buf, "n")] = '0'; printf("%zu", strlen(buf)); What is printed?
- Why must the result of getchar() be stored in an int rather than a char?
- Which call reads a line into char buf[100] safely?
- char name[10]; / input: a long name / scanf("%9s", name); What is the most characters stored before the terminator?
- Records (name, score, age) are sorted by score descending, and by age ascending for equal scores. Input: (A,90,30), (B,90,25), (C,85,20)…