DEV Community

swatiBabber
swatiBabber

Posted on

Array Rotation

Use array reversal for array rotation .
Use two pointer for array reversal.

public class Solution {
public void Rotate(int[] nums, int k) {
k=k% nums.Length;
k=k% nums.Length;
reverse(nums, 0, nums.Length-1);
reverse(nums,0, k-1);
reverse(nums,k,nums.Length-1);
}

void reverse(int[] nums, int start , int end)
{
    while(start<end)
    {
        int temp=nums[start];
        nums[start]=nums[end];
        nums[end]=temp;
        start++;
        end--;
    }
}
Enter fullscreen mode Exit fullscreen mode

}

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more