easy +10 pts

Rotate Left by k

Shift every element left by k positions, wrapping around the front to the back.

Write a function `rotate_left(arr, k)` that returns a new list which is the original list `arr` rotated to the left by `k` positions. Rotation means that each element moves `k` positions to the left, and elements that fall off the front are appended at the back. For example, rotating `[1, 2, 3, 4, 5]` left by 2 gives `[3, 4, 5, 1, 2]`. Assumptions: - `arr` is a list of any type (but comparisons are not needed). - `k` is a non-negative integer. - If `k` is larger than the length of `arr`, rotating by `k` is the same as rotating by `k % len(arr)` (if `arr` is not empty). - If `arr` is empty, return an empty list (any `k`). The function should return a new list and should not modify the original list.

Constraints

- `0 <= len(arr) <= 10^5` - `0 <= k <= 10^9` - Time complexity: O(n), where n is the length of `arr`. - Space complexity: O(n) for the returned list.

Example

>>> rotate_left([1, 2, 3, 4, 5], 2)
[3, 4, 5, 1, 2]
>>> rotate_left([1, 2, 3], 5)
[3, 1, 2]
>>> rotate_left([], 10)
[]
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use the modulo operator to reduce k when it exceeds the list length.
Consider slicing the list into two parts and concatenating them in the reverse order.
Be careful with the empty list case—return an empty list without indexing.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.