Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Rotate Right by 1

Rotate a list one position right with manual shifts. Students preserve the last value and scan backward to avoid overwriting values that are still needed.

IntermediatePhase 4 - Level 3: TransformationExample 8 of 10
rotate-right-by-1.py
1# Take array
2n = int(input("Enter array size: "))
3arr = []
4for i in range(n):
5 arr.append(int(input(f"Element {i+1}: ")))
6
7# Rotate right
8if len(arr) > 0:
9 last = arr[-1]
10 for i in range(len(arr) - 1, 0, -1):
11 arr[i] = arr[i - 1]
12 arr[0] = last
13
14print(f"After right rotation: {arr}")

Output

Enter array size: 5
Element 1: 1
Element 2: 2
Element 3: 3
Element 4: 4
Element 5: 5
After right rotation: [5, 1, 2, 3, 4]

In this one

  • Copy backward safely
  • Preserve an endpoint
  • Rotate without losing values

How it works

  1. 1

    Save the last value.

  2. 2

    Shift preceding values right using descending indexes.

  3. 3

    Write the saved value at index zero.

Edge cases

Why shift backward?

Why shift backward?

Forward shifts would overwrite later source values too early.

What happens for a one-element list?

What happens for a one-element list?

The shift loop is empty and the value is restored to itself.

What's going on

The last element is saved first. The loop then moves from the last index down to one, copying the previous element into each slot.

Moving backward preserves each source until it has been copied. Finally, arr[0] gets the saved last value. [1, 2, 3] becomes [3, 1, 2]. The guard makes empty lists safe; a single value rotates to itself.

Why shift backward? Forward shifts would overwrite later source values too early.

What happens for a one-element list? The shift loop is empty and the value is restored to itself.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Which value wraps to the front?

Pick an answer to check it.

Question 2

Why shift backward?

Pick an answer to check it.

Questions people ask

Why shift backward?

Forward shifts would overwrite later source values too early.

What happens for a one-element list?

The shift loop is empty and the value is restored to itself.

Which value wraps to the front?

The original last value.