Back to Practice Dashboard
DSA SectionEasy
Array Rotation
Learn how to solve the 'Array Rotation' problem. This detailed resource details brute force and optimized approaches.
Problem Statement
Easy
Write a function rotate_array(arr, k) that rotates the array arr to the left by k positions and returns the rotated array. Elements that go past the beginning wrap around to the end. For example, rotating [1,2,3,4,5] left by 2 gives [3,4,5,1,2].
Constraints
- •0 <= len(arr) <= 10^5
- •0 <= k <= 10^6
- •-10^9 <= arr[i] <= 10^9
Examples
Example 1
Input
arr = [1, 2, 3, 4, 5], k = 2
Output
[3, 4, 5, 1, 2]
Explanation
Rotate left by 2: first 2 elements [1,2] move to the end.
Example 2
Input
arr = [10, 20, 30, 40], k = 1
Output
[20, 30, 40, 10]
Explanation
Rotate left by 1: 10 moves to the end.
Example 3
Input
arr = [1, 2, 3], k = 3
Output
[1, 2, 3]
Explanation
Rotating by the array length returns the original array.
Need a Hint?
Analyze the input constraints. Try sorting first (O(n log n)) or using a hash map/set to track seen elements in O(n) time.
Edge Cases to Watch
- Empty list or null input variables
- Single item lists/arrays
- Extremely large input bounds causing integer or stack overflow
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.