Bird
Raised Fist0
DSA Goprogramming

Array Rotation Techniques in DSA Go

Choose your learning style10 modes available
Mental Model
Rotating an array means moving its elements so that some elements shift to the front or back, like spinning a circle of items.
Analogy: Imagine a merry-go-round with children sitting in a circle. Rotating the array is like spinning the merry-go-round so the children change seats but keep the same order relative to each other.
Array before rotation:
[1] -> [2] -> [3] -> [4] -> [5] -> null
Dry Run Walkthrough
Input: array: [1, 2, 3, 4, 5], rotate right by 2
Goal: Move the last 2 elements to the front, shifting others right
Step 1: reverse entire array
[5] -> [4] -> [3] -> [2] -> [1] -> null
Why: Reversing whole array prepares for splitting rotation parts
Step 2: reverse first 2 elements
[5] -> [4] -> [3] -> [2] -> [1] -> null
Why: Reversing first part restores order of rotated elements
Step 3: reverse remaining 3 elements
[5] -> [4] -> [1] -> [2] -> [3] -> null
Why: Reversing second part restores order of remaining elements
Result:
[5] -> [4] -> [1] -> [2] -> [3] -> null
Annotated Code
DSA Go
package main

import "fmt"

func reverse(arr []int, start, end int) {
    for start < end {
        arr[start], arr[end] = arr[end], arr[start] // swap elements
        start++ // move start forward
        end--   // move end backward
    }
}

func rotateRight(arr []int, k int) {
    n := len(arr)
    if n == 0 || k%n == 0 {
        return // no rotation needed
    }
    k = k % n // handle rotations larger than array size

    reverse(arr, 0, n-1) // reverse whole array
    reverse(arr, 0, k-1) // reverse first k elements
    reverse(arr, k, n-1) // reverse rest
}

func main() {
    arr := []int{1, 2, 3, 4, 5}
    rotateRight(arr, 2)
    for i, v := range arr {
        if i > 0 {
            fmt.Print(" -> ")
        }
        fmt.Print(v)
    }
    fmt.Println(" -> null")
}
arr[start], arr[end] = arr[end], arr[start] // swap elements
swap elements to reverse the subarray
start++ // move start forward
advance start pointer to continue reversing
end-- // move end backward
move end pointer backward to continue reversing
if n == 0 || k%n == 0 { return // no rotation needed }
handle empty array or full rotation (no change)
k = k % n // handle rotations larger than array size
normalize rotation steps within array length
reverse(arr, 0, n-1) // reverse whole array
reverse entire array to prepare for rotation
reverse(arr, 0, k-1) // reverse first k elements
reverse first part to restore rotated elements order
reverse(arr, k, n-1) // reverse rest
reverse remaining part to restore order
OutputSuccess
5 -> 4 -> 1 -> 2 -> 3 -> null
Complexity Analysis
Time: O(n) because each element is reversed at most twice during the rotation
Space: O(1) because rotation is done in place without extra arrays
vs Alternative: Naive approach shifts elements one by one in O(n*k) time, which is slower for large k
Edge Cases
empty array
function returns immediately without changes
DSA Go
if n == 0 || k%n == 0 {
        return // no rotation needed
    }
rotation by 0 or multiple of array length
array remains unchanged
DSA Go
if n == 0 || k%n == 0 {
        return // no rotation needed
    }
rotation larger than array length
rotation steps are normalized using modulo
DSA Go
k = k % n // handle rotations larger than array size
When to Use This Pattern
When you need to rotate or shift array elements efficiently, use the reverse method because it rotates in-place with minimal operations.
Common Mistakes
Mistake: Rotating by k without modulo causes index errors or unnecessary rotations
Fix: Always use k = k % n to normalize rotation steps
Mistake: Trying to rotate by moving elements one by one leads to slow O(n*k) time
Fix: Use the reverse method to achieve O(n) time
Summary
Rotates array elements by shifting them right or left using in-place reversals.
Use when you want to rotate arrays efficiently without extra space.
The key insight is that reversing parts of the array in a specific order achieves rotation.

Practice

(1/5)
1. What does rotating an array to the left by 1 position do to the elements?
easy
A. Reverses the entire array
B. Moves the last element to the front and shifts others right by one
C. Moves the first element to the end and shifts others left by one
D. Sorts the array in ascending order

Solution

  1. Step 1: Understand left rotation

    Left rotation by 1 means the element at index 0 moves to the end.
  2. Step 2: Effect on array elements

    All other elements shift one position to the left.
  3. Final Answer:

    Moves the first element to the end and shifts others left by one -> Option C
  4. Quick Check:

    Left rotate 1 = first element to end [OK]
Hint: Left rotate by 1 moves front element to back [OK]
Common Mistakes:
  • Confusing left rotation with right rotation
  • Thinking rotation sorts the array
  • Assuming rotation reverses the array
2. Which of the following Go code snippets correctly rotates an array arr to the right by 1 position?
easy
A. arr = append(arr[len(arr)-1:], arr[:len(arr)-1])
B. arr = append(arr[1:], arr[0])
C. arr = append(arr[:len(arr)-1], arr[len(arr)-1])
D. arr = append([]int{arr[len(arr)-1]}, arr[:len(arr)-1]...)

Solution

  1. Step 1: Understand right rotation by 1

    Right rotation by 1 moves last element to front.
  2. Step 2: Check code correctness

    arr = append([]int{arr[len(arr)-1]}, arr[:len(arr)-1]...) prepends last element to the rest correctly using slicing and append.
  3. Final Answer:

    arr = append([]int{arr[len(arr)-1]}, arr[:len(arr)-1]...) -> Option D
  4. Quick Check:

    Right rotate 1 = last element front [OK]
Hint: Right rotate by 1 prepends last element [OK]
Common Mistakes:
  • Using wrong slice indices
  • Appending single element without slice expansion
  • Confusing left and right rotation code
3. What is the output of the following Go code?
arr := []int{10, 20, 30, 40, 50}
k := 2
n := len(arr)
k = k % n
rotated := append(arr[n-k:], arr[:n-k]...)
fmt.Println(rotated)
medium
A. [40 50 10 20 30]
B. [30 40 50 10 20]
C. [20 30 40 50 10]
D. [50 10 20 30 40]

Solution

  1. Step 1: Calculate effective rotation

    k=2, n=5, so k%5=2 means rotate right by 2.
  2. Step 2: Perform rotation

    arr[n-k:] = arr[3:] = [40,50], arr[:n-k] = arr[:3] = [10,20,30]. Append gives [40,50,10,20,30].
  3. Final Answer:

    [40 50 10 20 30] -> Option A
  4. Quick Check:

    Right rotate 2 = last 2 front [OK]
Hint: Right rotate by k = last k elements front [OK]
Common Mistakes:
  • Not using modulo for k
  • Swapping slice indices incorrectly
  • Confusing left and right rotation
4. Identify the error in this Go code that attempts to left rotate an array by 3 positions:
arr := []int{1, 2, 3, 4, 5}
k := 3
rotated := append(arr[k:], arr[k:]...)
fmt.Println(rotated)
medium
A. The slice is appended twice from the same index, missing first part
B. The variable k is not used correctly for rotation
C. The array length is not considered for rotation
D. The append function is used incorrectly without slice expansion

Solution

  1. Step 1: Analyze append arguments

    Both slices are arr[k:], so elements from index 3 to end repeated twice.
  2. Step 2: Identify missing part

    Left rotation requires appending arr[:k] after arr[k:], but code repeats arr[k:] instead.
  3. Final Answer:

    The slice is appended twice from the same index, missing first part -> Option A
  4. Quick Check:

    Left rotate needs arr[k:] + arr[:k] [OK]
Hint: Append arr[k:] then arr[:k] for left rotation [OK]
Common Mistakes:
  • Appending same slice twice
  • Ignoring first k elements in rotation
  • Not using slice expansion operator
5. Given an array arr = []int{5, 10, 15, 20, 25, 30}, how would you rotate it left by 4 positions using Go slices? Choose the correct code snippet.
hard
A. rotated := append(arr[:4], arr[4:]...)
B. rotated := append(arr[4:], arr[:4]...)
C. rotated := append(arr[len(arr)-4:], arr[:len(arr)-4]...)
D. rotated := append(arr[len(arr)-4:], arr[len(arr)-4:]...)

Solution

  1. Step 1: Understand left rotation by 4

    Left rotation by 4 moves first 4 elements to the end.
  2. Step 2: Use slicing correctly

    arr[4:] gives elements from index 4 to end, arr[:4] gives first 4 elements. Append arr[4:] + arr[:4] rotates left by 4.
  3. Final Answer:

    rotated := append(arr[4:], arr[:4]...) -> Option B
  4. Quick Check:

    Left rotate 4 = arr[4:] + arr[:4] [OK]
Hint: Left rotate k = arr[k:] + arr[:k] [OK]
Common Mistakes:
  • Swapping slice order
  • Using wrong slice indices
  • Confusing left and right rotation
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard