703388. Rotating an Array
Rotating an Array
Summary
Given an array of integers, rotate it by a certain number of positions. For example, if the input array is [1, 2, 3, 4, 5] and we want to rotate it by 2 positions, the output would be [4, 5, 1, 2, 3]. This problem involves basic algorithms and data structures.
Detailed Explanation
The goal of this problem is to write a function that takes an array of integers and a number of positions as input, and returns the rotated array. We can solve this problem by using a simple algorithm that shifts the elements of the array by the given number of positions.
Here's a step-by-step breakdown of the solution:
- Take the input array and the number of positions as input.
- Create a new array to store the rotated result.
- Copy the last
n(number of positions) elements from the original array to the beginning of the new array, wherenis the number of positions. - Copy the remaining elements from the original array to the end of the new array.
Here's an ASCII art diagram to illustrate the process:
Original Array: [1, 2, 3, 4, 5]
Rotate by 2:
Last 2 elements -> [4, 5] (move them to the beginning)
Remaining elements -> [1, 2, 3]
New Array: [4, 5, 1, 2, 3]
Time complexity: O(n), where n is the length of the input array. We need to iterate through the entire array once. Space complexity: O(1), as we only use a constant amount of space to store the rotated result.
Optimized Solutions
Here are optimized solutions in different programming languages:
Java
public int[] rotateArray(int[] arr, int n) {
int[] result = new int[arr.length];
for (int i = n; i < arr.length; i++) {
result[i - n] = arr[i];
}
for (int i = 0; i < n; i++) {
result[i] = arr[arr.length - n + i];
}
return result;
}