703084. Quick Left Rotation
Basic
Quick Left Rotation
Slug: quick-left-rotation3806 Difficulty: Basic Id: 703084 Topic Tags: Arrays, Data Structures Company Tags: None
Summary
Given an array of integers and a rotation value k, perform a left rotation on the array by k positions. This means that elements at indices 0 to k-1 should be shifted to the end of the array.
Detailed Explanation
The problem can be solved using a straightforward algorithmic approach. We will create a new array with the same length as the input array and then populate it with the rotated elements.
Here's the step-by-step breakdown:
- Create an empty array
resultwith the same length as the input array. - Iterate from index
kto the end of the input array, inclusive. For each element at indexi, place it at the beginning of theresultarray (at index(i-k)%n, wherenis the length of the input array). - Copy the remaining elements from the input array (from index 0 to
k-1) to the end of theresultarray.
Here's an ASCII art diagram illustrating the rotation:
Input: [1, 2, 3, 4, 5]
Rotation: 2
Result: [3, 4, 5, 1, 2]
Time complexity analysis:
- The algorithm iterates through the input array once, so the time complexity is O(n), where
nis the length of the input array.
Space complexity analysis:
- We create a new array to store the rotated elements, which has the same length as the input array. Therefore, the space complexity is O(n).
Optimized Solutions
Java
public int[] quickLeftRotation(int[] arr, int k) {
int n = arr.length;
int[] result = new int[n];
for (int i = k; i < n; i++) {
result[(i-k)%n] = arr[i];
}
for (int i = 0; i < k; i++) {
result[i] = arr[n-i-1];
}
return result;
}