Search code examples
pythoniteratorpalindromeiterablespace-complexity

Find palindrome python space complexity?


Given the following code in python which checks whether an string of n size is palindromic:

def is_palindromic(s):
    return all(s[i] == s[~i] for i in range(len(s) // 2))

What is the space complexity of this code? Is it O(1) or O(n)?

The all function gets an iterable as a parameter;

So does it mean the s[i] == s[~i] for i in range(len(s) // 2) expression is an iterable (container) that stores n values in memory?

Or maybe it behaves like an iterator that computes and returns the values one by one without any additional space?


Solution

  • You are using a generator expression, which only needs enough memory to store one item at a time.

    The other parts, len, range and the all function itself are all O(1) too, so your suggestion that "it behaves like an iterator that computes and returns the values one by one without any additional space" is correct.

    If you used a list expression instead

    all([s[i] == s[~i] for i in range(len(s) // 2)])
    

    it would briefly use O(n) memory to build the list, which would be passed as a parameter to all.