ProgrammingModerate
Which of these is an O(n) method to test whether a string of length n is a palindrome in C?
- A. Reversing the string into a new buffer with strrev and comparing, which is O(n) but unsafe in standard C
- B. Comparing every pair of characters, which is O(n^2)
- C. Sorting the characters and comparing with the original, O(n log n)
- 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
- char s[] = "hello world"; char w = strchr(s, ' ') + 1; printf("%s", w); What is printed?
- char a[8] = "abc"; memset(a + 1, 'z', 2); printf("%s", a); What is printed?
- char s[] = "12abc"; char end; long v = strtol(s, &end, 10); printf("%c", end); What is printed?
- char buf[3]; int n = snprintf(buf, 3, "%s", "hello"); printf("%d", n); What is printed?
- char p = "abc"; printf("%d", (p + 3)); What is printed?
- char s[] = "A1b2"; int d = 0; for (int i = 0; s[i]; i++) if (s[i] >= '0' && s[i] <= '9') d++; printf("%d", d); What is printed?