DEV Community is a community of 786,090 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

[Binary Search]Rotate List Left by K

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

Example 2

Input

nums = [1, 2, 3, 4, 5, 6]
k = 6

Example 3

nums = 
k = 0

Output: 

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--;
}
}
}