简体   繁体   中英

Time and Space Complexity of python function

Can you please help me with how to calculate space and time complexity for below code

def isPalindrome(string):
    # Write your code here.
    string1=string[::-1]
    if string1==string:
        return True
    else :
        return False

The easiest way to find complexity is to go line by line and under each operation.

Let's start with the first line

string1=string[::-1]

This is a string slicing operation, which reverses the string and according to this , it takes time proportional to the number of characters which is being copied, in this case (your code) it is the whole string, hence it will be O(n) This is just line 1. Let's move ahead

if string1==string:

here we are doing a string comparison, in the condition section of the if statement. according to this , it is again O(n) for line 2

now, the following lines are just return and else block which will be done in constant time ie O(1)

hence for the total complexity, we just sum up all the line's complexity. ie O(n) + O(n) + O(1) + O(1)

you can refer to this to learn more about simplifying it.

So the final time complexity will be O(n)

This function can be broken down into complexity of its sub-processes. In calculating this time complexity, let the amount of characters in string be n ( n = len(string ) in Python terms). Now, let's look at the 2 sub-processes:

  1. Traverse all characters in string in reverse order and assign to string1 (this is done by string1=string[::-1] ) - O(n) linear time since there are n characters in string .
  2. Compare if string1 == string - O(n) linear time because n characters in each string will be compared to each other, so that is n 1-to-1 comparisons.

Therefore, the total time complexity is O(n) + O(n) where n is len(string) . In shorter terms, we simplify this to mean O(n) complexity .

The following two operations decides the time complexity of the above code:

  1. With the below operation you are creating a copy of the list in the reversed manner which takes O(n) time and O(n) space:

     string1 = string[::-1]
  2. Checking the strings in the below line for equality again takes O(n) operations as you need to compare all the characters in the worst case:

     if string1==string:

From the above, we can conclude the following:

Time complexity: O(n)

Space complexity: O(n)

where n represents the length of the input string.

You would also like go through this document which summarizes the time complexities for different operations in Python.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM