Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rotate Array #60

Open
kokocan12 opened this issue Jul 11, 2022 · 0 comments
Open

Rotate Array #60

kokocan12 opened this issue Jul 11, 2022 · 0 comments
Assignees

Comments

@kokocan12
Copy link
Owner

kokocan12 commented Jul 11, 2022

Problem

When an array is given, rotate the array by k steps.

example
Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]

Approach

First, flip the elements in array right and left.
If nums = [1,2,3,4,5,6], the fliped nums is [6,5,4,3,2,1].
Then divide left, right portion by k, [6,5] [4,3,2,1] (k is 2 in this case).
Swap each portion. [5,6] [1,2,3,4].

The code is below

const rotate = function(nums, k) {
    k = k % nums.length;
    
    // Swap all elements.
    let left = 0;
    let right = nums.length - 1;
    
    while(left < right) {
        swap(nums, left, right);
        left += 1;
        right -= 1;
    }
    
    // Swap left portion elements.
    left = 0;
    right = k-1;
    while(left < right) {
        swap(nums, left, right);
        left += 1;
        right -= 1;
    }
    
    // Swap right portion elements.
    left = k;
    right = nums.length - 1;
    while(left < right) {
        swap(nums, left, right);
        left += 1;
        right -= 1;
    }
    
};

function swap(nums, i, j) {
    const temp = nums[i];
    nums[i] = nums[j];
    nums[j] = temp;
}
@kokocan12 kokocan12 self-assigned this Jul 11, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant