ProgrammingModerateAmazon OA · Flipkart coding round

Which is the time complexity of checking whether a string s of length n is a palindrome, using s == s[::-1]?

  1. A. O(1) time, because string comparison is constant time
  2. B. O(n log n) time, because slicing sorts the characters
  3. C. O(n^2) time, because each slice step copies the string
  4. D. O(n) time and O(n) extra space, because the reversed copy is built in full

Correct answer: D. O(n) time and O(n) extra space, because the reversed copy is built in full

s[::-1] builds a new string of length n, which costs O(n) time and O(n) extra space. Comparing the two strings is also O(n) in the worst case.

More Python Programming questions

Exams that ask this topic