Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Problem No 20

Rotate List by N Positions

Medium

15 minute session

Summary

Rotate a list by n positions. Positive n rotates to the right, negative n rotates to the left.

Problem statement

Implement rotate_list(lst, n) that returns a new list which is the input list rotated by n positions. A positive n means rotate to the right; a negative n means rotate to the left. Rotation should wrap around and handle |n| larger than the list length. The original list must not be mutated.

Task

Practice index arithmetic, modular arithmetic, and handling edge cases like empty lists or n larger than list length.

Examples

Right rotation

Input

rotate_list([1, 2, 3, 4, 5], 2)

Output

[4, 5, 1, 2, 3]

Explanation

Each element moves two positions to the right; the last two wrap to the front.

Input format

Two arguments: lst (a list) and n (an integer).

Output format

A new list rotated by n positions.

Constraints

Do not use external libraries. Aim for O(n) time and O(n) extra space for the returned list. The input list may be empty.

Samples

Sample input 0

rotate_list([1, 2, 3], -1)

Sample output 0

[2, 3, 1]

Explanation 0

Negative n rotates left by 1.

Code editor
Loading editor…

AI assistant

Ask me anything!

Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.

Chat history is temporary and will not be saved.

03:46 AM

Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.