DEV Community

Cover image for LeetCode Challenge: 189. Rotate Array - JavaScript Solution πŸš€
Rahul Kumar Barnwal
Rahul Kumar Barnwal

Posted on β€’ Edited on

2 1 1 1 1

LeetCode Challenge: 189. Rotate Array - JavaScript Solution πŸš€

Top Interview 150

Rotating an array is a fundamental problem that tests your ability to optimize space and time usage. Let's tackle LeetCode 189: Rotate Array, understand its nuances, and implement an efficient solution.


πŸš€ Problem Description

Given an integer array nums, rotate the array to the right by k steps.

  • Key Constraints:
    • Perform the rotation in-place, meaning no extra array for storage.
    • 1 ≀ nums.length ≀ 10*5

πŸ’‘ Examples

Example 1

Input: nums = [1,2,3,4,5,6,7], k = 3  
Output: [5,6,7,1,2,3,4]  
Enter fullscreen mode Exit fullscreen mode

Example 2

Input: nums = [-1,-100,3,99], k = 2  
Output: [3,99,-1,-100]
Enter fullscreen mode Exit fullscreen mode

🧠 Key Insights

  • Circular Rotation: Rotating by k steps is equivalent to slicing and concatenating, but achieving this in-place is tricky.
  • Modular Arithmetic: Since rotating by k steps is the same as rotating by k % nums.length, unnecessary full rotations can be avoided.

πŸ† JavaScript Solution

This solution uses a reverse strategy for optimal in-place rotation.

Reverse Strategy

  1. Reverse the entire array.
  2. Reverse the first k elements.
  3. Reverse the remaining elements.
var rotate = function(nums, k) {
    k = k % nums.length;
    if (k === 0) return;

    reverse(nums, 0, nums.length - 1);
    reverse(nums, 0, k - 1);
    reverse(nums, k, nums.length - 1);
};

function reverse(arr, start, end) {
    while (start < end) {
        [arr[start], arr[end]] = [arr[end], arr[start]];        
        start++;
        end--;
    }
}
Enter fullscreen mode Exit fullscreen mode

πŸ” How It Works

  • Reverse the array:
    Turns [1,2,3,4,5,6,7] into [7,6,5,4,3,2,1].

  • Reverse the first k elements:
    Turns [7,6,5] into [5,6,7].

  • Reverse the rest:
    Turns [4,3,2,1] into [1,2,3,4].
    Final Output: [5,6,7,1,2,3,4].


πŸ”‘ Complexity Analysis

  • > Time Complexity: O(n), as each reverse operation takes O(n), and there are three operations.
  • > Space Complexity:O(1), as no extra memory is used.

πŸ“‹ Dry Run

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


✨ Pro Tips for Interviews

  1. Understand modular arithmetic: Reducing k to k % nums.length is crucial for efficiency.
  2. Edge cases: Consider arrays with one element or when k = 0.
  3. Explain the reverse strategy: It’s optimal and clean for in-place array rotation.

πŸ“š Learn More

For a detailed walkthrough and explanation, check out my Dev.to post:
πŸ‘‰ Majority Element - JavaScript Solution

Let me know your thoughts! How would you approach this problem? πŸš€

JavaScript #LeetCode #CodingInterview #ProblemSolving

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (1)

Collapse
 
rahulgithubweb profile image
Rahul Kumar Barnwal β€’

Follow Me on GitHub πŸš€

If you found this solution helpful, check out more of my projects and solutions on my GitHub profile.

Don't forget to follow for more updates!

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

πŸ‘‹ Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay