40.Rotate an Array in Python | Left & Right Rotation by K Steps

Опубликовано: 27 Июнь 2026
на канале: LEARN CODE EASILY
46
6

In this tutorial, you’ll learn how to rotate an array to the left or right by k steps in Python — step by step, without using slicing shortcuts.

👉 What you’ll learn:

The difference between left rotation and right rotation

How to implement both manually using loops & modulo

Step-by-step dry run explanation

Common interview variations of array rotation

💡 This is a must-know coding interview question for Data Structures & Algorithms (DSA).

🔔 Subscribe for more Python & DSA tutorials!


---------------------------------------------
🚀 Program: Rotate an Array by K Steps
---------------------------------------------

def rotate_array(arr, k, direction="right"):
n = len(arr) # Length of array

if n == 0: # Edge case: empty array
return arr

k = k % n # Normalize k
rotated = [0] * n

for i in range(n):
if direction == "right":
Right rotation
new_index = (i + k) % n
else:
Left rotation
new_index = (i - k) % n

rotated[new_index] = arr[i]

return rotated


---------------------------------------------
✅ Example usage
---------------------------------------------
arr = [1, 2, 3, 4, 5, 6, 7]

print("Right Rotation by 3:", rotate_array(arr, 3, "right"))
[5, 6, 7, 1, 2, 3, 4]

print("Left Rotation by 3:", rotate_array(arr, 3, "left"))
[4, 5, 6, 7, 1, 2, 3]
#Python #LearnPython #PythonProgramming #Coding #DSA #ArrayRotation #PythonForBeginners #InterviewPreparation #CodingInterview #LeetCode #DataStructures #Algorithms #PythonTutorial #RotateArray #ProblemSolving