Mark As Completed Discussion

Try this exercise. Click the correct answer from the options.

What is the run time of the following code?

PYTHON
1def reverse_str(str):
2  start = 0
3  end = len(str)-1
4  str_copy = [letter for letter in str]
5  while start < end:
6    temp = str_copy[start]
7    str_copy[start] = str_copy[end]
8    str_copy[end] = temp
9    start += 1
10    end -= 1
11  return "".join(str_copy)

Complexity of Final Solution

Let n be the length of the string. We iterate n/2 times until the left pointer is greater than the right pointer for linear O(n) time complexity, and we use a constant O(1) space for the 2 pointers.

Click the option that best answers the question.

  • O(log n)
  • O(n)
  • O(n log n)
  • O(n^2)