Reputation: 527
Does reversing part of the array in the following manner create a copy of array from i to j?
a[i:j] = a[i:j][::-1] # is this in place? Does this operation require O(j-i) space
Does following code not take any extra space?
a[i:j] = reversed(a[i,j])
So is there any other way to reverse part of list with O(1) space apart from following code?
for k in range(i, i + (j-i + 1)//2):
arr[k], arr[j-k] = arr[j-k], arr[k]
Upvotes: 1
Views: 241
Reputation: 530930
Kind of. a
is modified in place, but a[i:j]
creates a new list object, as does applying [::-1]
to a[i:j]
.
b = a[i:j] # new list object
b = b[::-1] # another new list object
a[i:j] = b # modifies a in place
Upvotes: 3