2

I'm working on a leetcode problem where you rotate an array.

"Given an array, rotate the array to the right by k steps, where k is non-negative."

In the solution I'm trying, I slice the array, getting the last k elements and the first n-k elements. This is stored in a tuple, then assigned to the first k elements and last n-k elements, respectively (code shown below).

Is this solution O(1) time and O(1) space, or does the slicing operation and tuple/simultaneous assignment have extra time/space costs that I'm not aware of?

def rotate(self, nums: List[int], k: int) -> None:

    k = k% len(nums)

        if k>0:
    nums[:k],nums[k:] = nums[-k:], nums[:-k]

1 Answer 1

1

As said here Big-O of list slicing , array slicing in Python is not in O(1) since it's backed by an array behind.

Your algorithm would therefore be in O(k) since you read k elements 2 times and write k elements 2 times to your array.

Sign up to request clarification or add additional context in comments.

1 Comment

That's really helpful, thanks. I think it would actually be O(n) since I would be slicing k elements and n-k elements, and I suppose the space complexity would be O(n) for that reason as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.