Rotate Array Solution for Accenture

Company: Accenture · Difficulty: Medium · Topics: Array, Two Pointers, Math

Problem Statement

Given an array, rotate the array to the right by k steps, where k is non-negative.

Key Understanding:

Examples

Example 1:

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

Output: [5,6,7,1,2,3,4]

Explanation:

Example 2:

Input: nums = [-1,-100,3,99], k = 2

Output: [3,99,-1,-100]

Explanation:

Example 3:

Input: nums = [1,2,3], k = 4

Output: [3,1,2]

Explanation:

Intuition

The key insight is that rotating an array by k steps is equivalent to:

1. Reversing the entire array

2. Reversing the first k elements

3. Reversing the remaining n-k elements

Mathematical Insight:

Why Three Reversals Work:

Approach

Approach 1: Using Extra Array (Simple)

Algorithm:

1. Create a new array of same size

2. Copy elements to new positions: newArr[(i + k) % n] = arr[i]

3. Copy back to original array

Approach 2: Juggling Algorithm

Algorithm:

1. Move elements in cycles

2. For each cycle, move elements by k positions

3. Continue until all elements are moved

Approach 3: Reversal Algorithm (Optimal)

Algorithm:

1. Reverse the entire array

2. Reverse the first k elements

3. Reverse the remaining n-k elements

Dry Run

Let's trace through Example 1: nums = [1,2,3,4,5,6,7], k = 3

Reversal Approach:

Extra Array Approach:

Key Insights

1. Modulo Operation: k % n gives effective rotation

2. Three Reversals: Efficient in-place solution

3. Cyclic Nature: Elements wrap around the array

4. Edge Cases: Handle k > n and k = 0

Edge Cases

1. k = 0: No rotation needed

2. k = n: Array returns to original state

3. k > n: Use modulo to get effective rotation

4. n = 1: Single element array

5. k = 1: Simple one-step rotation

Solution

⚠️ Disclaimer: Don't jump directly to the solution, try it out yourself first. Only look at the solution after you've given it a good attempt.

Solution 1: Reversal Algorithm (Optimal)

Time Complexity: O(n) - Three passes through array

Space Complexity: O(1) - In-place solution

Solution 2: Extra Array

Time Complexity: O(n) - Two passes through array

Space Complexity: O(n) - Extra array needed

Solution 3: Juggling Algorithm

Time Complexity: O(n) - Single pass through array

Space Complexity: O(1) - In-place solution

More Accenture coding questions