Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Rotate a sequence using deque

Use collections.deque.rotate to rotate sequences efficiently and preserve type.

Python practice18 minModules & Standard LibraryIntermediateLast updated March 23, 2026

Problem statement

Write a function rotate(seq, k) that returns the sequence rotated to the right by k steps. If k is negative, rotate to the left. Use collections.deque and its rotate method for efficiency. The function should preserve the input type for lists and strings. For other sequence types you may return a list representing the rotated elements.

Task

Implement rotate(seq, k) that rotates a sequence by k positions using collections.deque. For lists return a list; for strings return a string.

Examples

Rotate a list right by 1

Input

rotate([1, 2, 3, 4], 1)

Output

[4, 1, 2, 3]

Right rotation by 1 moves the last element to the front.

Input format

A sequence (list or string) and an integer k: rotate(seq, k)

Output format

A rotated sequence of the same type (list -> list, string -> string).

Constraints

Use collections.deque.rotate for O(n) rotation with minimal overhead. Handle empty sequences and k values larger than the length by relying on deque behavior.

Samples

Sample 1

Input

rotate('abcd', 2)

Output

cdab

Right rotate string by 2: 'ab' moves to the end, resulting in 'cdab'.