Reverse string time and space complexity

人走茶凉 提交于 2020-01-11 06:09:43

问题


I have written different python codes to reverse a given string. But, couldn't able to figure the which one among them is efficient. Can someone point out the differences between these algorithms using time and space complexities?

def reverse_1(s):
      result = ""
      for i in s : 
          result = i + result
      return result

def reverse_2(s): 
      return s[::-1]

There are already some solutions out there, but I couldn't find out the time and space complexity. I would like to know how much space s[::-1] will take?


回答1:


Without even trying to bench it (you can do it easily), reverse_1 would be dead slow because of many things:

  • loop with index
  • constantly adding character to string, creating a copy each time.

So, slow because of loop & indexes, O(n*n) time complexity because of the string copies, O(n) complexity because it uses extra memory to create temp strings (which are hopefully garbage collected in the loop).

On the other hand s[::-1]:

  • doesn't use a visible loop
  • returns a string without the need to convert from/to list
  • uses compiled code from python runtime

So you cannot beat it in terms of time & space complexity and speed.

If you want an alternative you can use:

''.join(reversed(s))

but that will be slower than s[::-1] (it has to create a list so join can build a string back). It's interesting when other transformations are required than reversing the string.

Note that unlike C or C++ languages (as far as the analogy goes for strings) it is not possible to reverse the string with O(1) space complexity because of the immutability of strings: you need twice the memory because string operations cannot be done in-place (this can be done on list of characters, but the str <=> list conversions use memory)




回答2:


Complexity Operation | Example | Class | Notes --------------+--------------+---------------+------------------------------- Iteration | for v in l: | O(N) | Worst: no return/break in loop Slice | l[a:b] | O(b-a) | l[1:5]:O(l)/l[:]:O(len(l)-0)=O(N)

The second one is better!

Source: https://www.ics.uci.edu/~pattis/ICS-33/lectures/complexitypython.txt



来源:https://stackoverflow.com/questions/51335422/reverse-string-time-and-space-complexity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!