Taro Logo

Rotate Array

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+27
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
1.3K views
Topics:
Arrays

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

Example 1:

Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]

Example 2:

Input: nums = [-1,-100,3,99], k = 2
Output: [3,99,-1,-100]
Explanation: 
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]

Constraints:

  • 1 <= nums.length <= 105
  • -231 <= nums[i] <= 231 - 1
  • 0 <= k <= 105

Follow up:

  • Try to come up with as many solutions as you can. There are at least three different ways to solve this problem.
  • Could you do it in-place with O(1) extra space?

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the range of values for $k$, and can $k$ be larger than the length of the array?
  2. How should we handle edge cases such as an empty array, a null input, or an array with a single element?
  3. Can $k$ be a negative integer, and if so, how should a negative rotation be interpreted?
  4. Are there any constraints on memory usage, or is modifying the array in-place strictly required without allocating auxiliary arrays of size $O(n)$?
  5. Does the rotation need to be performed in-place strictly, or is returning a new array acceptable if memory isn't strictly constrained?

Brute Force Solution

Approach

Imagine you have a row of items and you want to shift them all to the right by a certain number of steps, so that the items falling off the right side wrap around to the front. The brute force approach achieves this by repeatedly moving just the very last item to the front of the row, one single shift at a time.

Here's how the algorithm would work step-by-step:

  1. Look at the item sitting at the very end of the row.
  2. Take that item out from the end and hold it in your hand.
  3. Slide every other item in the row one spot to the right to make room at the front.
  4. Place the item you were holding into the newly created open spot at the very beginning of the row.
  5. Repeat this entire process from the beginning for however many total steps you need to shift the row.

Code Implementation

def rotate_array_brute_force(elements, step_count):
    # Normalize step count to avoid redundant full rotations over the entire list length
    normalized_steps = step_count % len(elements)

    for current_step in range(normalized_steps):
        # Extract the last element because it must be moved to the front during a right shift
        last_element = elements[-1]

        for current_index in range(len(elements) - 1, 0, -1):
            elements[current_index] = elements[current_index - 1]

        # Place the extracted element at the front to complete one single rotation step
        elements[0] = last_element

    return elements

Big(O) Analysis

Time Complexity
O(n * k) – To rotate the array by k steps, we repeat the shift operation k times. During each of the k iterations, we must traverse and move all n elements of the array one position to the right. This leads to approximately n * k total operations, which simplifies to O(n * k) in the worst case where k can be on the order of n.
Space Complexity
O(1) – The provided algorithm performs all shifts in place directly on the original row of items without allocating any new auxiliary data structures. The process relies entirely on a single temporary variable held in hand to temporarily store the shifted item, requiring a constant amount of extra memory regardless of the input size. Because no additional arrays, lists, or recursive call stacks are created that scale with the input length, the auxiliary space remains fixed. Therefore, the total extra memory simplifies to a constant time-space footprint of Big O of 1.

Optimal Solution

Approach

Instead of moving items one by one or making a copy of everything, the optimal approach uses a clever sequence of reversals to rearrange the collection in place. By flipping specific portions of the group and then the whole group, everything naturally lands in its final shifted position.

Here's how the algorithm would work step-by-step:

  1. First, look at how far the items need to be shifted and isolate the final section of items that wraps around to the front.
  2. Reverse the order of this entire collection from start to finish so that the items are backwards.
  3. Next, take the first portion of the collection up to the shift point and reverse just that section so those items face the correct way again.
  4. Finally, take the remaining portion of the collection and reverse just that section as well.
  5. By performing these three simple reversals, all the items end up in their exact correct positions without wasting extra memory.

Code Implementation

class Solution:
    def rotate(self, collection_items: list[int], shift_distance: int) -> None:
        collection_length = len(collection_items)
        effective_shift = shift_distance % collection_length

        # Normalizing the shift distance ensures we do not perform redundant full-length rotations.
        def reverse_subsegment(start_index: int, end_index: int) -> None:
            while start_index < end_index:
                collection_items[start_index], collection_items[end_index] = collection_items[end_index], collection_items[start_index]
                start_index += 1
                end_index -= 1

        # Reversing the entire collection places the wrapping elements at the front in reversed order.
        reverse_subsegment(0, collection_length - 1)

        # Reversing the first segment restores the correct internal sequence of the shifted elements.
        reverse_subsegment(0, effective_shift - 1)

        # Reversing the remaining segment restores the correct internal sequence of the tail elements.
        reverse_subsegment(effective_shift, collection_length - 1)

Big(O) Analysis

Time Complexity
O(n) – The time complexity is driven by the three separate reversal steps acting directly on the input array of size n. Reversing the entire array takes roughly n/2 operations, and reversing the two individual partitions collectively covers the remaining elements once more. This results in a total of approximately 2n operations across the reversals. By dropping constants and scaling factors, the overall runtime simplifies to O(n).
Space Complexity
O(1) – The algorithm performs all reversals directly on the original input array in place without allocating any additional data structures. Only a few primitive pointer variables are used to track indices during the reversal process, meaning the memory footprint remains constant regardless of the input size N. Consequently, the auxiliary space complexity is O(1).

Edge Cases

k is greater than the length of the array
How to Handle:
We take k modulo the array length to avoid redundant full rotations and out of bound errors.
k is equal to zero
How to Handle:
Modulo operation results in zero, leaving the array completely unchanged as expected.
Array contains only a single element
How to Handle:
Any value of k results in modulo zero, safely returning the single element array untouched.
Empty or null input array
How to Handle:
We add an initial guard clause to immediately return before performing any operations.
k is a negative number
How to Handle:
We add the array length to k after modulo to correctly handle left rotations as equivalent right rotations.
Array with maximum constraint length and maximum k value
How to Handle:
Using the in-place array reversal algorithm ensures O(1) extra space complexity without memory limit issues.
Array containing all identical values
How to Handle:
The rotation logic still executes completely, maintaining the identical state of the array seamlessly.
Array containing negative numbers and extreme boundary values
How to Handle:
The swap and shift operations treat values as opaque elements, preserving their signs and magnitudes.
0/75 completed