Find palindrome python space complexity?
Question:
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?
Answers:
range(len(s) // 2)
is O(1)
space, and the documentation on all() says that all
is equivalent to
def all(iterable):
for element in iterable:
if not element:
return False
return True
This has space complexity O(1)
.
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
.
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?
range(len(s) // 2)
is O(1)
space, and the documentation on all() says that all
is equivalent to
def all(iterable):
for element in iterable:
if not element:
return False
return True
This has space complexity O(1)
.
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
.