ProgrammingModerate

Which of these is an O(n) method to test whether a string of length n is a palindrome in C?

  1. A. Reversing the string into a new buffer with strrev and comparing, which is O(n) but unsafe in standard C
  2. B. Comparing every pair of characters, which is O(n^2)
  3. C. Sorting the characters and comparing with the original, O(n log n)
  4. D. Two indices from both ends, comparing s[i] with s[j] and computing the length once

Correct answer: D. Two indices from both ends, comparing s[i] with s[j] and computing the length once

Two indices meet in the middle, touching each character once. Reversing into a buffer is O(n) too, but strrev is not standard C, and the pair test is quadratic.

More C Programming questions

Exams that ask this topic