https://binarysearch.com/problems/Rotate-List-Left-by-K
Write a function that rotates a list of numbers to the left by k elements. Numbers should wrap around.
Note: The list is guaranteed to have at least one element, and k is guaranteed to be less than or equal to the length of the list.
Bonus: Do this without creating a copy of the list. How many swap or move operations do you need?
Constraints
n ≤ 100,000
where n is the length of nums
Example 1
Input:
nums = [1, 2, 3, 4, 5, 6]
k = 2
Output: [3, 4, 5, 6, 1, 2]
Example 2
Input
nums = [1, 2, 3, 4, 5, 6]
k = 6
Output: [1, 2, 3, 4, 5, 6]
Example 3
Input
nums = [1]
k = 0
Output: [1]
class Solution {
public int[] solve(int[] nums, int k) {
rotate(nums, 0, k - 1);
rotate(nums, k, nums.length - 1);
rotate(nums, 0, nums.length - 1);
return nums;
}
private void rotate(int[] nums, int left, int right) {
while (left < right) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
left++;
right--;
}
}
}
Top comments (0)