I have a function that takes an input string of characters and reverses them according to the white space breaks.
For example:
input: arr = [ 'p', 'e', 'r', 'f', 'e', 'c', 't', ' ',
'm', 'a', 'k', 'e', 's', ' ',
'p', 'r', 'a', 'c', 't', 'i', 'c', 'e' ]
output: [ 'p', 'r', 'a', 'c', 't', 'i', 'c', 'e', ' ',
'm', 'a', 'k', 'e', 's', ' ',
'p', 'e', 'r', 'f', 'e', 'c', 't' ]
To reverse the 'words', I use the following function
def reverse_word(arr):
i = 0
j = len(arr) - 1
while i < j:
arr[j], arr[i] = arr[i], arr[j]
i += 1
j -= 1
return arr
def reverse_words(arr):
arr.reverse()
p1 = 0
for i, v in enumerate(arr):
if v == ' ':
if arr[p1] != ' ':
arr[p1:i] = reverse_word(arr[p1:i])
p1 = i + 1
arr[p1:] = reverse_word(arr[p1:])
return arr
My question is: Is the call to reverse an O(1) or O(N) space operation? I assumed O(N) but someone else said it was O(1). I assumed O(N) because in the worst case, with one word, the entire array will need to be copied to the stackcall. Space is not "constant" because the space size allocated to the call is dependent on the input length.