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?

  1. A. int n = strlen(s); for (int i = 0; i < n / 2; i++) swap(&s[i], &s[strlen(s) - 1 - i]);
  2. B. for (int i = 0; i < strlen(s); i++) swap(&s[i], &s[strlen(s) - 1 - i]);
  3. C. int n = strlen(s); for (int i = 0, j = n - 1; i < j; i++, j--) swap(&s[i], &s[j]);
  4. 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

Exams that ask this topic