01: Introduction

“Learning how to rotate array by k positions in Python is a milestone for every programmer. If you’ve been solving array problems, you’ve definitely come across this challenge.It’s one of those questions that looks deceptively simple — but if you don’t know the trick, you’ll waste time in an interview.

So what exactly is array rotation in Python? Simple — imagine your array is a circular track. Rotating it means moving every element by k steps either to the left or to the right. The elements that fall off one end come back from the other.

For example, think of a music playlist. When you skip 2 songs forward, the first two songs move to the end of the queue. That’s array rotation in real life.

This problem is asked in companies like Amazon, Infosys, TCS, Wipro, and Google because it tests your understanding of arrays, modulo arithmetic, and in-place algorithms — all fundamentals for any software engineer.

⚡ Quick Answer (Featured Snippet)

Rotating an array by k positions means shifting all elements left or right by k places. Always use k = k % n to handle large values of k. Python slicing solves it in O(n) time, while the reversal algorithm does it in-place with O(1) extra space.

02: Problem Statement

Given an array arr of n elements and an integer k, rotate the array by k positions.

  • Left Rotation: Elements shift towards the left. The first k elements move to the end.
  • Right Rotation: Elements shift towards the right. The last k elements move to the beginning.

Example 1 — Left Rotation

Input  : arr = [1, 2, 3, 4, 5],  k = 2
Left   : [3, 4, 5, 1, 2]   ← elements shifted 2 places to the left

Example 2 — Right Rotation

Input : arr = [1, 2, 3, 4, 5], k = 2

Right  : [4, 5, 1, 2, 3]   ← elements shifted 2 places to the right

Input / Output Format

  • Line 1: Integer n — size of the array
  • Line 2: n space-separated integers
  • Line 3: Integer k — number of positions to rotate
  • Output: The rotated array printed space-separated

Constraints

  • 1 ≤ n ≤ 105
  • 0 ≤ k ≤ 109
  • −109 ≤ arr[i] ≤ 109
📌 Note

Since k can be very large (even larger than n), always compute k = k % n first. If k becomes 0 after this, the array stays unchanged.

03: Why This Problem Is Important

Array rotation isn’t just a textbook exercise — it shows up in real systems all the time:

  • 🎵 Music Playlist: Cycling through songs in a loop
  • 🖥️ CPU Round-Robin Scheduling: Each process gets a turn in a rotating queue
  • 📷 Image Processing: Shifting pixel rows/columns for effects
  • 💾 Circular Buffers: Used in networking and OS memory management
  • 🎮 Game Turns: Rotating players in a multiplayer game
  • 📡 Signal Processing: Shifting sample windows in streaming data

Understanding this problem deeply helps you tackle harder problems like search in rotated sorted array, next permutation, and sliding window algorithms.

04: Naive Approach — One Step at a Time

The simplest idea: rotate by 1 position, k times. For a left rotation by 1, pop the first element and append it to the end. Repeat this k times.

def naive_left_rotate(arr, k):
    n = len(arr)
    k = k % n
    for _ in range(k):
        first = arr[0]          # store first element
        arr = arr[1:] + [first] # shift left by 1
    return arr

This works, but it’s slow. Every single rotation is O(n), and you do it k times — giving O(n × k) total time. If n = 100,000 and k = 50,000, that’s 5 billion operations. Not interview-friendly at all.

⚠️ Interview Warning

Never submit the naive approach in an interview unless you mention it as a starting point and immediately propose a better solution. Interviewers expect O(n).

05: Optimal Approach 1 — Python Slicing Method

Rotate Array by k Positions in Python Using Slicing
This is the most Pythonic and readable solution. The idea is simple: split the array at index k and swap the two parts.

  • Left rotate: arr[k:] + arr[:k]
  • Right rotate: arr[n-k:] + arr[:n-k]
arr = [1, 2, 3, 4, 5]
k = 2
n = len(arr)
k = k % n   # handle k > n

left_rotated  = arr[k:] + arr[:k]   # [3, 4, 5, 1, 2]
right_rotated = arr[n-k:] + arr[:n-k] # [4, 5, 1, 2, 3]

Clean, readable, and runs in O(n) time. The only trade-off is that it uses O(n) extra space for the new list. For most practical use cases and interviews, this is perfectly acceptable.

06: Optimal Approach 2 — Reversal Algorithm

This is the gold standard for interviews. It rotates in-place with O(1) extra space. Here’s the trick for left rotation by k:

  1. Reverse the first k elements
  2. Reverse the remaining n-k elements
  3. Reverse the entire array

For arr = [1,2,3,4,5], k = 2:

STEP-BY-STEP

Original      : [1, 2, 3, 4, 5]
Step 1 (rev 0..k-1) : [2, 1, 3, 4, 5]
Step 2 (rev k..n-1) : [2, 1, 5, 4, 3]
Step 3 (rev all)    : [3, 4, 5, 1, 2]  ✓ Left rotated!

PYTHON — REVERSAL ALGORITHM

def reverse(arr, left, right):
    while left < right:
        arr[left], arr[right] = arr[right], arr[left]
        left  += 1
        right -= 1

def left_rotate_reversal(arr, k):
    n = len(arr)
    k = k % n
    reverse(arr, 0, k - 1)   # reverse first k elements
    reverse(arr, k, n - 1)   # reverse remaining elements
    reverse(arr, 0, n - 1)   # reverse entire array
    return arr

This uses O(n) time, O(1) space — the best you can do for this problem.

07: Flowchart

Rotate Array by k Positions in Python

08: Pseudocode

FUNCTION rotate_array(arr, k, direction):
    n ← length(arr)
    IF n == 0 THEN RETURN arr

    k ← k MOD n
    IF k == 0 THEN RETURN arr

    IF direction == "left" THEN
        RETURN arr[k..n-1] + arr[0..k-1]
    ELSE IF direction == "right" THEN
        RETURN arr[n-k..n-1] + arr[0..n-k-1]

END FUNCTION

09: Complete Python Program

Complete Program to Rotate Array by k Positions in Python

def left_rotate(arr, k):
    """Left rotate array by k positions using slicing."""
    n = len(arr)
    if n == 0: return arr
    k = k % n              # handle k > n
    return arr[k:] + arr[:k]

def right_rotate(arr, k):
    """Right rotate array by k positions using slicing."""
    n = len(arr)
    if n == 0: return arr
    k = k % n              # handle k > n
    return arr[n - k:] + arr[:n - k]

def left_rotate_inplace(arr, k):
    """Left rotate using reversal algorithm — O(1) space."""
    n = len(arr)
    if n == 0: return arr
    k = k % n

    def reverse(a, l, r):
        while l < r:
            a[l], a[r] = a[r], a[l]
            l += 1; r -= 1

    reverse(arr, 0, k - 1)
    reverse(arr, k, n - 1)
    reverse(arr, 0, n - 1)
    return arr


n   = int(input("Enter array size: "))
arr = list(map(int, input("Enter elements: ").split()))
k   = int(input("Enter k: "))

print("Left Rotate  :", left_rotate(arr[:], k))
print("Right Rotate :", right_rotate(arr[:], k))
print("Left (In-place):", left_rotate_inplace(arr[:], k))

Sample Output

OUTPUT

Enter array size: 5
Enter elements: 1 2 3 4 5
Enter k: 2

Left Rotate   : [3, 4, 5, 1, 2]
Right Rotate  : [4, 5, 1, 2, 3]
Left (In-place): [3, 4, 5, 1, 2]

10: Dry Run — Step by Step

Let’s trace arr = [1, 2, 3, 4, 5], k = 2 manually.

Left Rotation (Slicing)

Step Operation Result
1 k = 2 % 5 k = 2
2 arr[2:] [3, 4, 5]
3 arr[:2] [1, 2]
4 Concatenate [3, 4, 5, 1, 2] ✓

Right Rotation (Slicing)

Step Operation Result
1 k = 2 % 5 k = 2
2 n – k = 5 – 2 = 3 split at index 3
3 arr[3:] [4, 5]
4 arr[:3] [1, 2, 3]
5 Concatenate [4, 5, 1, 2, 3] ✓

Left Rotation (Reversal Algorithm)

Step Operation Array State
Start [1, 2, 3, 4, 5]
1 Reverse arr[0..1] [2, 1, 3, 4, 5]
2 Reverse arr[2..4] [2, 1, 5, 4, 3]
3 Reverse arr[0..4] [3, 4, 5, 1, 2] ✓

11: Time & Space Complexity

Method Time Space Best For
Naive (1-step) O(n × k) O(1) Understanding only
Slicing O(n) O(n) Quick Python code
Reversal Algorithm O(n) O(1) Interviews ✓

The reversal algorithm is best in interviews because it gives O(n) time AND O(1) space — modifying the array in place with no extra memory. The slicing method, while clean, creates a new list in memory.

12: Test Cases & Edge Cases

# Input k Left Output Right Output
1 [1,2,3,4,5] 2 [3,4,5,1,2] [4,5,1,2,3]
2 [1,2,3,4,5] 0 [1,2,3,4,5] [1,2,3,4,5]
3 [1,2,3,4,5] 5 [1,2,3,4,5] [1,2,3,4,5]
4 [1,2,3,4,5] 7 [3,4,5,1,2] [4,5,1,2,3]
5 [42] 99 [42] [42]
6 [] 3 [] []
🔍 Edge Case Notes

k = 0 or k = n: Always returns the original array. k > n: Use k % n — rotation wraps around. Single element: Any rotation gives the same array. Empty array: Return empty, don’t crash.

13: Common Interview Questions

Q: Why do we use k % n?

Because if k = n, the array returns to its original state. Rotating n times = no change. Using k % n avoids unnecessary work and prevents index out-of-range errors.

Q: What’s the best method in interviews?

The reversal algorithm — it runs in O(n) time with O(1) extra space. Always explain the slicing method first as a readable solution, then propose reversal for optimal space.

Q: Difference between left and right rotation?

Left rotation removes from the front and adds to the back. Right rotation removes from the back and adds to the front. Right rotate by k = Left rotate by (n – k).

Q: Can we rotate in-place?

Yes! The reversal algorithm modifies the original array without creating a new one. Python slicing always creates a new list, so it’s not truly in-place.

Q: Which companies ask this?

Amazon, Microsoft, Adobe, Infosys, Wipro, TCS, Google (in array manipulation rounds), and almost every company with a DSA interview round.

14: Mistakes Beginners Make

  • Forgetting k % n — causes wrong output when k > n
  • Wrong slicing index for right rotation — use arr[n-k:], not arr[-k:] (they work the same but -k can confuse you)
  • Confusing left and right — always test with a small example before coding
  • Not handling empty array — will crash with ZeroDivisionError on k % n
  • Mutating original array accidentally — use arr[:] to pass a copy
  • Naive approach in interview — O(n×k) will fail large test cases

15: FAQ

Array rotation means shifting all elements of an array by a certain number of positions (k) either to the left or to the right. Elements that go past one end reappear at the other end — like a circular arrangement.

Because rotating an array of size n exactly n times brings it back to the original state. So rotating by k is the same as rotating by k % n. It also prevents index errors when k is larger than the array size.

Left rotation shifts all elements towards the beginning — the first k elements move to the end. Right rotation shifts elements towards the end — the last k elements come to the front. Right rotate by k = Left rotate by (n – k).

For clean code: use slicing — arr[k:] + arr[:k]. For interviews and optimal space: use the reversal algorithm which works in O(n) time and O(1) space.

Yes, using the reversal algorithm. It directly swaps elements within the original array without creating a new list, keeping space complexity at O(1). Python’s slicing method creates a new array, so it’s not truly in-place.

Absolutely. It’s a fundamental array manipulation problem asked at Amazon, Microsoft, Infosys, TCS, and Wipro. It also underpins harder problems like “search in rotated sorted array” and “maximum rotation sum.”

Conclusion

You’ve now learned everything about rotate an array by k positions in Python — from the basic naive approach all the way to the optimal reversal algorithm used in real interviews.

The key takeaways: always compute k = k % n first, use slicing for readable code, and switch to the reversal algorithm when space matters. Handle edge cases like empty arrays and k = 0 before anything else.

Practice this problem on LeetCode (#189 – Rotate Array) and you’ll build strong muscle memory for array problems. Now you know the best ways to rotate array by k positions in Python. Happy coding! 🚀