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]?
- A. O(1) time, because string comparison is constant time
- B. O(n log n) time, because slicing sorts the characters
- C. O(n^2) time, because each slice step copies the string
- 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
- What is printed? python values = [0, 1, 2, 3] print([v for v in values if v] == values[1:], any(values), all(values[1:]))
- What is printed? python import heapq nums = [7, 2, 9] heapq.heapify(nums) print(nums[0], heapq.nlargest(1, nums)[0], heapq.nsmallest(2…
- What is printed? python print(any(x > 3 for x in range(10)), next(x for x in range(10) if x x > 20), sum(x for x in range(0, 10, 4)))
- What is printed? python s = '12:34:56' h, m, sec = map(int, s.split(':')) print(h 3600 + m 60 + sec, divmod(h 3600 + m 60 + sec, 60))
- What is printed? python print([x % 3 for x in [-7, -3, 0, 4]])
- What is printed? python def counter(): count = 0 def step(): nonlocal count count += 2 return count return step c1 = counter() c2 =…